【问题标题】:Redux state change in componentWillMount is not be recognized in componentDidMount?componentWillMount 中的 Redux 状态更改在 componentDidMount 中无法识别?
【发布时间】:2016-08-11 23:31:48
【问题描述】:

需要加载我的主要组件,如果存在具有“logged: true”对值的本地存储,请使用 react-router 重定向到“/app”。

我正在使用 react-redux,这是我的代码:

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>
    );
  }
}

我的 redux 操作:

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

但是当组件进入componentDidMount阶段时,我的redux状态仍然没有更新。

Y 设法让这个工作通过使用:

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

但我不确定这是最优雅的解决方案。

提前致谢!

【问题讨论】:

    标签: reactjs redux lifecycle react-redux


    【解决方案1】:

    使用componentWillReceiveProps 是这里的方法,因为您的 logStatus 对象正在作为正在更改的道具传递。

    使用Redux-thunk middleware 有一种更优雅的方法,它允许您调度一个函数(接收dispatch 作为参数而不是对象操作。然后您可以将该函数包装在一个promise 中并使用它在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 中间件专为此类用例而设计。

    【讨论】:

      猜你喜欢
      • 2019-01-19
      • 2020-12-20
      • 1970-01-01
      • 2017-04-24
      • 2017-03-05
      • 1970-01-01
      • 1970-01-01
      • 2018-10-02
      • 1970-01-01
      相关资源
      最近更新 更多