簡體   English   中英

React Router 4.x-連接到Redux后PrivateRoute不起作用

[英]React Router 4.x - PrivateRoute not working after connecting to Redux

與Redux連接后,示例https://reacttraining.com/react-router/web/example/auth-workflow中可用的PrivateRoute不起作用。

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

與@Tharaka答案互補的是,您可以通過{pure: false}connect方法,如react-redux故障排除一節所述

React-reduxshouldComponentUpdate掛鈎中對道具進行了淺層比較,以避免不必要的重新渲染。 如果上下文道具更改(反應路由器),則不會進行檢查,並且假定沒有任何更改。

{ pure:false }僅禁用此淺表比較。

根據react-router文檔,您可以將connect函數包裝在withRouter

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

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

這對我有用。

這是react-redux中的已知問題,您可以在此處閱讀有關此內容的更多信息。 問題是connect HoC已經實現了shouldComponentUpdate ,因此,如果不更改props ,包裝的組件不會shouldComponentUpdate 由於react-router使用上下文傳遞路由更改,因此在路由更改時不會重新包裝組件。 但是似乎他們打算在react-redux的5.1版本中刪除shouldComponentUpdate 目前,作為一種解決方法,我將諸如this.props.match.params類的來自Router的prop傳遞給了連接的子組件,即使我沒有在內部使用它。 但是,每次更改路線時,都會重新渲染組件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM