13

示例https://reacttraining.com/react-router/web/example/auth-workflow中提供的 PrivateRoute 在与 Redux 连接后无法正常工作。

我的 PrivateRoute 看起来与原始版本几乎相同,但仅连接到 Redux并使用它而不是原始示例中的 fakeAuth。

const PrivateRoute = ({ component: Component, auth, ...rest }) => (
  <Route
   {...rest}
   render={props =>
   auth.isAuthenticated
    ? <Component {...props} />
    : <Redirect to={{ pathname: "/login" }} />}
  />
);

 PrivateRoute.propTypes = {
  auth: PropTypes.object.isRequired,
  component: PropTypes.func.isRequired
 }

 const mapStateToProps = (state, ownProps) => {
  return {
     auth: state.auth
  }
};

export default connect(mapStateToProps)(PrivateRoute);

用法和结果:-

  1. 不工作但希望和期望工作
    • <PrivateRoute path="/member" component={MemberPage} />
  2. 工作但不希望这样使用
    • <PrivateRoute path="/member" component={MemberPage} auth={auth} />
  3. 在职的。只是工作,但根本不想使用。从这一点的理解是,如果您将原始 PrivateRoute 连接到 Redux,您需要传递一些额外的道具(任何道具)以使 PrivateRoute 工作,否则它不起作用。任何人,请对这种行为给出一些提示。这是我的主要问题
    • <PrivateRoute path="/member" component={MemberPage} anyprop={{a:1}} />
4

3 回答 3

12

作为@Tharaka 答案的补充,您可以传递{pure: false}react-redux 故障排除部分connect中所述的方法。

React-redux对钩子中的 props 进行了浅层比较,shouldComponentUpdate以避免不必要的重新渲染。如果上下文道具发生了变化(react-router),它不会检查它并假设没有任何变化。

{ pure:false }只是禁用这种浅比较。

于 2017-06-15T10:53:12.483 回答
8

根据react-router 文档,您可以将connect函数包装为withRouter

// before
export default connect(mapStateToProps)(Something)

// after
import { withRouter } from 'react-router-dom'
export default withRouter(connect(mapStateToProps)(Something))

这对我有用。

于 2017-10-04T03:42:57.243 回答
7

这是 react-redux 中的已知问题,您可以在此处阅读更多相关信息。问题是connectHoC 已经实现,因此如果不更改shouldComponentUpdate,包装的组件不会重新呈现。props由于 react-router 使用上下文来传递路由更改,因此当路由更改时,包装的组件不会重新渲染。但似乎他们将shouldComponentUpdate5.1 版本的 react-redux 中删除。目前,作为一种解决方法,我将来自 Router 的 prop 传递this.props.match.params给连接的子组件,即使我没有在内部使用它。但是每次路由改变时都会重新渲染组件。

于 2017-05-10T12:27:58.060 回答