reactjs - redux(用户认证)更新后React渲染私有(private)路由

标签 reactjs redux react-router

PrivateRoute 在 Redux 从服务器获取当前用户数据之前进行渲染。解决此问题的最佳方法是什么?

该组件如下所示。 userAuth.isAuthenticated最终更新为true但它呈现 <Redirect to="/login" />在更新之前先。

const userAuth = {
  isAuthenticated: false
}

const PrivateRoute = ({ component: Component, ...rest }) => (
  <Route {...rest} render={(props) => (
    // PROBLEM: this renders before Redux gets user authentication data from the server
    userAuth.isAuthenticated ? <Component {...props} /> : <Redirect to="/login" />
  )}/>
)

class App extends Component {
  componentDidMount() {
    // Get current user data when user refresh the browser
    // This sets isLoginSuccess: true is current user is logged-in in Redux store
    this.props.getCurrentUserSession();
  }

  render() {
    // Show loading icon while fetching current user data
    if(this.props.user.isFetchingCurrentUserSession){
      return (<div><img src={squareLogo} className="logo-loading" alt="Loading icon" /></div>);
    }

    // Set current user authentication status
    userAuth.isAuthenticated = this.props.user.isLoginSuccess

    return (
      <Router>
        <div>
          <Route path="/public" component={Public} />
          <PrivateRoute path="/private" component={Private} />
        </div>
      </Router>
    );
  }
}

function mapStateToProps(state) {
  return state
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators({
    getCurrentUserSession
  }, dispatch);
}

export default connect(mapStateToProps, mapDispatchToProps)(App)

最佳答案

你可以这样做:

1.初始化isAuthenticated为null

2.in render return 使用私有(private)组件的条件渲染

const userAuth = {
 isAuthenticated: null
}

在应用程序渲染中返回:

return (
  <Router>
    <div>
      <Route path="/public" component={Public} />
      {(userAuth.isAuthenticated!==null)?<PrivateRoute path="/private" 
      component={Private} />:null}
    </div>
  </Router>
);

关于reactjs - redux(用户认证)更新后React渲染私有(private)路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50499768/

相关文章:

javascript - React-redux,连接函数不使用新数据更新状态

javascript - redux-saga 中的选择问题。错误 : call: argument of type {context, fn} 具有未定义或空 `fn`

reactjs - React 路由器 (v4) 导航栏

javascript - 如何使 React Native Webview 自动高度

javascript - TypeError : this. $el.DataTable 不是一个函数( REACT.JS)

javascript - 根据状态或点击事件更改文本颜色

mysql - useSelector 函数不更新分派(dispatch)函数后的状态 - react Hook

reactjs - <Switch> 内特定路由的上下文提供者

javascript - 使用 React、react-router、jest 和 enzyme 测试状态变化

reactjs - pusher .bind 方法中的过时 react 状态