【发布时间】:2020-12-14 20:52:36
【问题描述】:
我正在尝试使用受保护的路由来防止未经身份验证的用户看到页面。为此,每次重新加载页面时,我都会连接到服务器以检查令牌并查看用户是否经过身份验证,并在服务器响应时更新 Redux 状态。这工作正常,但是当我尝试更新受保护的路由组件时出现问题。由于服务器响应延迟,组件第一次渲染默认状态值为false,但是当我获得服务器响应并将Redux状态更新为true时,我的组件不会重新渲染
function ProtectedRoute(props, {component: Component, ...rest}){
return (
<Route
{...rest}
render={props =>{
if(props.userLoginStatus){
console.log('protected if')
return <Component {...props} />
} else {
console.log('protected else')
return <Redirect to={{
pathname: '/forbidden',
state: {from: props.location}
}}
/>
}
}}
/>
)
}
const mapStateToProps = (state) => {
return {
userLoginStatus: state.userLoginReducer.userLogin
}
}
export default connect(mapStateToProps)(ProtectedRoute)
【问题讨论】:
标签: javascript reactjs api redux router