Reactjs 更新redux(用户身份验证)后反应呈现私有路由

Reactjs 更新redux(用户身份验证)后反应呈现私有路由,reactjs,redux,react-router,Reactjs,Redux,React Router,PrivateRoute在Redux从服务器获取当前用户数据之前呈现。解决此问题的最佳方法是什么 组件如下所示userAuth.isAuthenticated最终更新为true,但它在更新之前先呈现 const userAuth = { isAuthenticated: false } const PrivateRoute = ({ component: Component, ...rest }) => ( <Route {...rest} render={(props)

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

组件如下所示
userAuth.isAuthenticated
最终更新为
true
,但它在更新之前先呈现

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)
const userAuth={
I验证:错误
}
const privaterout=({component:component,…rest})=>(
(
//问题:这会在Redux从服务器获取用户身份验证数据之前呈现
userAuth.isAuthenticated?:
)}/>
)
类应用程序扩展组件{
componentDidMount(){
//在用户刷新浏览器时获取当前用户数据
//这将设置IsLoginSucess:如果当前用户登录到Redux存储,则为true
this.props.getCurrentUserSession();
}
render(){
//获取当前用户数据时显示加载图标
if(this.props.user.isFetchingCurrentUserSession){
返回();
}
//设置当前用户身份验证状态
userAuth.isAuthenticated=this.props.user.isloginsucess
返回(
);
}
}
函数MapStateTops(状态){
返回状态
}
功能图DispatchToprops(调度){
返回bindActionCreators({
getCurrentUserSession
},派遣);
}
导出默认连接(mapStateToProps、mapDispatchToProps)(应用程序)
您可以这样做:

1.初始化isAuthenticated为null

2.在渲染返回中,使用私有组件的条件渲染

const userAuth = {
 isAuthenticated: null
}
应用程序内渲染返回:

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

这是您的实际代码吗?@devserkanYes,代码的一部分。您为什么不直接将IsLoginSAccess传递给PrivateRoute?也只是实现了这一点。使用
null
false
true
isAuthenticated
进行验证,同样适用于Redux。但是,当在
交换机底部使用catch-all重定向时,使用相同的逻辑来装载整个
交换机
可能比使用
专用路由
更有用。同样的逻辑也可用于菜单。