2016-08-11 68 views
1

需要加载我的主要组件,并且如果使用react-router将对值“logged:true”的本地存储重定向到“/ app”。componentWidMount中的Redux状态更改在componentDidMount中无法识别?

我使用的反应,终极版,这是我的代码:

class Main extends Component { 

    componentWillMount(){ 
// Return true in redux state if localstorage is found 
     this.props.checkLogStatus(); 
    } 

    componentDidMount(){ 
// redirect in case redux state returns logged = true 
     if(this.props.logStatus.logged){ 
      hashHistory.push('/app'); 
     } 
    } 

    render() { 
    return (
    <App centered={true} className="_main"> 
     {this.props.children} 
    </App> 
    ); 
    } 
} 

我的终极版动作:

checkLogStatus() { 
    // check if user is logged and set it to state 
    return { 
     type: LOGIN_STATUS, 
     payload: window.localStorage.sugarlockLogged === "true" 
    }; 
} 

但是,当组件获得的componentDidMount阶段,我的终极版状态到现在还没有已更新。

Ÿ设法得到这种利用工作:

componentWillReceiveProps(nextProps){ 
     if (nextProps.logStatus.logged && nextProps.logStatus.logged !== this.props.logStatus.logged){ 
      hashHistory.push('/app'); 
     } 
    } 

但我不知道这是最好的解决方法。

提前致谢!

回答

0

使用componentWillReceiveProps是这里的方法,因为你的logStatus对象被作为一个正在被改变的道具传入。

还有就是这是一个更优雅的方式使用Redux-thunk middleware它允许你派一个函数(其接收dispatch作为参数,而不是对象的动作。然后,您可以换行功能的承诺,并在componentWillMount使用它。

在你的行动文件:

updateReduxStore(data) { 
    return { 
     type: LOGIN_STATUS, 
     payload: data.logInCheck 
    }; 
} 

validateLocalStorage() { 
    ... 
} 

checkLogStatus() { 
    return function(dispatch) { 
     return new Promise((resolve, reject) => { 
      validateLocalStorage().then((data) => { 
       if (JSON.parse(data).length > 0) { 
        dispatch(updateReduxStore(data)); 
        resolve('valid login'); 
       } else { 
        reject('invalid login'); 
       } 
      }); 
     }); 
    }; 
} 

然后在您的组件:

componentWillMount() { 
    this.props.checkLogStatus() 
     .then((message) => { 
      console.log(message); //valid login 
      hashHistory.push('/app'); 
     }) 
     .catch((err) => { 
      console.log(err); //invalid login 
     }); 
} 

Redux-thunk中间件用于这种用例。

相关问题