【问题标题】:How to dispatch an action based on a condition in side a router如何根据路由器侧的条件调度操作
【发布时间】:2018-04-02 14:03:30
【问题描述】:

如何以正确的方式根据条件调度操作: 我执行以下操作,但出现语法错误。


const PrivateRoute = ({ component: Component, ...rest }) => {
     <Route {...rest} render={props => (
          firebase.auth().onAuthStateChanged((user) => user
          ?(
            store.dispatch(actions.login(user.uid));
            <Component  {...props}/>
          )
          :(
            store.dispatch(actions.logout());
            <Redirect to={{
                pathname: '/login',
                state: { from: props.location }
              }}/>
            )
          )
        )}/>
      }

【问题讨论】:

    标签: reactjs firebase redux react-redux react-router-v4


    【解决方案1】:

    正则括号 ((..)) 让您返回一个值。这就是您的语法错误的原因。您应该执行以下操作。

    const PrivateRoute = ({ component: Component, ...rest }) => {
    
      // return the Route component
      return <Route {...rest} render={props => {
        firebase.auth().onAuthStateChanged((user) => {
          if(user) {
    
            // run dispatch
            store.dispatch(actions.login(user.uid));
            // return component
            return <Component  {...props} />
    
          } else {
    
            // run dispatch
            store.dispatch(actions.logout());
            // return component
            return <Redirect to={{ pathname: '/login', state: { from: props.location } }} />
    
          }
        });
      }} />  
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-06
      • 2017-07-17
      • 1970-01-01
      • 1970-01-01
      • 2020-01-03
      相关资源
      最近更新 更多