我正在开发一个使用 React Router 的应用程序,我注意到当我的 Redux 存储更改状态时,路由器正在重新渲染当前路由引用的组件,而不是重新渲染路由本身。
为了说明问题;我已经实现了一个 PrivateRoute
来检查用户当前是否登录。在它的最基本形式中,它看起来像这样:
const PrivateRoute = ({component: Component, ...rest}) => {
return <Route {...rest} render={(props) => {
const state = store.getState()
if (state.isAuthenticated) {
return <Component {...props}/>
}
else {
return <Redirect to={{pathname: '/login'}}/
}
}}/>
})
这很好用,因为我现在可以这样说了:
<PrivateRoute path="/" component={HomePage}/>
但是,我注意到当 isAuthenticated
的状态发生变化时,React Router 正在调用 HomePage
组件上的 render
方法,而不是那个它重新呈现路线。这意味着应用程序只会在用户从某个页面转到主页时进行身份验证检查,但一旦进入主页,就不再执行检查。
目前我唯一的解决方法是将身份验证检查移到组件的 render
函数中(这显然不属于它所属的位置)。
当状态改变时,如何让 React Router 重新渲染路由而不是重新渲染路由引用的组件?
最佳答案
我设法通过使用高阶组件而不是在路由中实现身份验证检查来解决问题。
function withEnsureAuthentication(WrappedComponent) {
return class extends React.Component {
render() {
if (this.props.store.isAuthenticated === false) {
return <Redirect to={{pathname: '/login'}}/>
}
return <WrappedComponent {...this.props}/>
}
}
}
您现在可以使用普通的 Route
但将 withEnsureAuthentication
应用于组件:
const HomePage = withEnsureAuthentication(Home)
<Route path="/home" component={HomePage}/>
关于javascript - React Router 重新渲染路由而不是重新渲染组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47743608/