我有这个元素的商店:
loggedIn:false
我想做的是阻止尚未登录的用户进入任何页面。 成功登录后,其他组件上的布尔值将变为true。
为了阻止他访问我的应用程序的其他链接,我创建了一个名为Refresh Route的组件来执行此操作:
import React from "react";
import { connect } from "react-redux";
import { Route, Redirect } from "react-router-dom";
const RefreshRoute = ({ component: Component, ...rest }) => {
const canGo=this.props.loggedIn;
window.alert(canGo)
return (<Route
{...rest}
render={props =>
canGo ? (
<Component {...props} />
) : (
<Redirect
to={{
pathname: "/login"
}}
/>
)
}
/>)
}
const mapStateToProps = state => {
return {
loggedIn: state.atuth.loggedIn
}
}
export default connect(mapStateToProps)(RefreshRoute);
我的问题是道具为空,我不知道为什么。
这里是我称为“刷新路线”的组件:
const Routes = () => (
<main>
<Switch>
<Route exact path='/' component={Main} />
<Route exact path='/customers' component={Customers} />
<Route exact path='/customers/:market' component={CustomersByMarket} />
<Route exact path='/customers/:market/:customer' component={Customer} />
<Route exact path='/customers/:market/:customer/:environment' component={MessageDashboard} />
<RefreshRoute exact path='/home' component={Main}/>
<Route exact path='/addPermission' component={AddPermissions}/>
<Route exact path='/excludePermission' component={RemovePermissions}/>
<Route exact path='/login' component={SignIn}/>
</Switch>
)
导出默认路由;
答案 0 :(得分:1)
在功能组件中您没有this.props
,因此请更改:
const RefreshRoute = ({ component: Component, ...rest }) => {
const canGo=this.props.loggedIn; // props is not bound to this
...
}
收件人:
const RefreshRoute = (props) => {
const canGo = props.loggedIn
}
或者您的情况:
const RefreshRoute = ({ component: Component, ...rest }) => {
const canGo = rest.loggedIn
}
答案 1 :(得分:1)
问题在这里:
const RefreshRoute = ({ component: Component, ...rest }) => {
const canGo=this.props.loggedIn;
您正在使用props
破坏输入{ component: Component, ...rest }
。因此属性loggedIn
将位于rest.loggedIn
内:
const RefreshRoute = ({ component: Component, ...rest }) => {
const canGo = rest.loggedIn;
否则,您可以在分解后的参数中显式显示loggedIn
并使用它:
const RefreshRoute = ({ component: Component, loggedIn, ...rest }) => {
const canGo = loggedIn;