首页 文章

React Router重新渲染路径而不是重新渲染组件

提问于
浏览
1

我正在使用一个使用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路由器正在 HomePage 组件上调用 render 方法,而不是重新渲染路由 . 这意味着应用程序仅在用户从某个页面转到主页时才进行身份验证检查,但是一旦在主页上,则不再执行检查 .

我目前唯一的工作是将身份验证检查移动到组件的 render 函数中(显然不是它所属的位置) .

如何让React Router重新渲染路由,而不是重新渲染路径在状态发生变化时引用的组件?

1 回答

  • 1

    我设法通过使用更高阶组件而不是在路由中实现身份验证检查来解决问题 .

    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}/>
    

相关问题