Render方法在react路由器v4中返回null

时间:2017-05-07 06:57:39

标签: reactjs redux react-router react-router-redux redux-router

我正在尝试使用react-router v4和redux实现私有路由,但渲染道具由于某种原因返回null。如果有人帮助我找出问题所在,我将非常感激。 路由器:

const router = (
          <Provider store={store}>
            <BrowserRouter history={history}>
              <App>
                <Route exact path="/" component={UserGrid}/>
                <Route path="/login" component={Login}/>
                <Route exact path="/users/:userId" component={UserPage}/>
                <Route path="/registration" component={RegistrationPage}/>
                <TopSecretRoute path="/topSecret" component={SecretComponent}/>
              </App>
            </BrowserRouter>
          </Provider>

TopSecretRoute.js:

const TopSecretRoute = ({ component: Component, ...rest }) => (
  <Route {...rest} render={props => (
    props.session.registered ? (
      <Component {...props}/>
    ) : (
      <Redirect to={{
        pathname: '/login',
        state: { from: props.location }
      }}/>
    )
  )}/>
)

const stateToProps = ['session']
export default createContainer(stateToProps,TopSecretRoute)

enter image description here

2 个答案:

答案 0 :(得分:2)

您可能遇到了React Router与Update Blocking的问题。这是因为Redux避免重新渲染并调用mapStateToProps。

为防止出现这种情况,您可以在react-redux connect函数中传递选项pure: false

示例:

connect(mapStateToProps, null, null, { pure: false })(Component);

您可以前往React Redux API documentation查看有关此选项的更多详情。

答案 1 :(得分:0)

您也可以使用withRouter

import { withRouter } from 'react-router-dom';
.
.
export default withRouter(connect(mapStateToProps)(AppRoutes));

参考-

  1. https://github.com/ReactTraining/react-router/issues/4671
  2. https://reacttraining.com/react-router/web/api/withRouter