如果用户未登录,我试图使以下链接不可访问:
<PrivateRoute path="/page" exact component={page}/>
React返回此代码错误:
const PrivateRoute = ({component: Component, ...rest}) => (
<Route {...rest} render={(props) => (
this.props.isAuthenticated === true
? <Component {...props} />
: <Redirect to='/login'/>
)}/>
);
还有is.Authenticated
部分
const mapStateToProps = state => {
return {
isAuthenticated: state.token !== null
};
};
TypeError:无法读取未定义的属性“ props”
我正在尝试访问函数isAuthenticated
中从我的mapStateToProps
传递过来的PrivateRoute
,我该怎么做?
答案 0 :(得分:1)
首先,您应该使用rest
代替this.props(未定义)
rest.isAuthenticated === true
而不是:
this.props.isAuthenticated === true
然后,您必须将道具传递到私人路线,如下所示:
<PrivateRoute isAuthenticated={some_variable_here}> // According to your validation logic
答案 1 :(得分:1)
尝试一下:
const PrivateRoute = ({component: Component, ...rest}) => (
<Route {...rest} render={() => (
!!rest.isAuthenticated === true
? <Component {...rest} />
: <Redirect to='/login'/>
)}/>
);
答案 2 :(得分:0)
我结合@Emanuele和@Sultan创建了答案。
因此,我首先从
更改了PrivateRoute
<PrivateRoute path="/page" exact component={page}/>
到
<PrivateRoute path="/page" exact component={page} auth={this.props.isAuthenticated}/>
通过这种方式,我可以从mapStateToProps
的{{1}}中传递值
然后,我编辑了函数PrivateRoute
,以从PrivateRoute
获取auth的值。现在看起来像这样
PrivateRoute
现在const PrivateRoute = ({component: Component, ...rest}) => (
<Route {...rest} render={(props) => (
rest.auth !== false
? <Component {...props}/>
: <Redirect to='/'/>
)}/>
);
函数已经知道从连接传递的privateRoute
值