1

我正在尝试使用 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)

在此处输入图像描述

4

2 回答 2

2

你可能正面临 React Router 的Update Blocking问题。发生这种情况是因为 Redux 避免了重新渲染并改为调用 mapStateToProps。

为了防止这种行为,您可以pure: false在 react-redux 连接函数中传递选项。

例子:

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

您可以前往React Redux API 文档以查看有关此选项的更多详细信息。

于 2017-05-07T17:10:47.560 回答
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
于 2018-08-31T18:12:22.283 回答