如何使用React HOC进行身份验证路由?

问题描述 投票:0回答:1

我正在尝试将私有路由添加到我的应用中,但是我收到此错误:

“不变失败:你不应该在<Route>之外使用<Router>

这是我的代码:

App.js

class App extends Component {
    render() {
        return (
            <BrowserRouter>
                <Route render={({ history }) => (
                    <div className="App">
                        <Navbar history={history} />
                        <Switch>
                            <Auth path="/" component={HomePage} currUser={this.props.currUser} />
                            <Route path="/login" render={(props) => (<LoginPage {...props} login={this.props.login} />)} />
                        </Switch>
                    </div>
                )} />
            </BrowserRouter>
        );
    }
}

const Auth = ({ component: Component, ...rest }) => {
    const {currUser} = rest;
    return (
        <Route {...rest} render=
            {props =>
                currUser ?
                    (<Component {...props} currUser={currUser.name} />) :
                    (<Redirect to={{ pathname: "/login", state: currUser }} />)
            } />
    )
}

const mapStateToProps = (state) => {
    return {
        currUser: state.auth.currUser
    }
}

const mapDispatchToProps = {
    ...authActions,
}

export default connect(mapStateToProps, mapDispatchToProps)(Auth);

我究竟做错了什么?如何将道具从Redux状态传递给此方法中的组件?

谢谢!

reactjs react-redux react-router
1个回答
0
投票

你用Auth组件包装了App组件,因此你的文件应该导出App。当您仅导出Auth时,<Route>中的Auth标记位于路由器标记之外。

export default connect(mapStateToProps, mapDispatchToProps)(App);
© www.soinside.com 2019 - 2024. All rights reserved.