更新 Redux 状态不会触发 componentWillReceiveProps [英] Updating Redux state does not trigger componentWillReceiveProps

查看:30
本文介绍了更新 Redux 状态不会触发 componentWillReceiveProps的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试验证登录信息.确保登录有效后,我想启动一条新路由.我通过 state.loginReducer.login 作为道具.当我处理提交事件时,会调度一个操作,更改全局登录状态.

I'm trying to validate the login information. After making sure the login is valid I want to fire a new route. I pass the state.loginReducer.login as props. When I handle the submit event, an action is dispatched, changing the global login state.

在这种情况下不应该触发 ComponentWillReceiveProps 吗?自从道具变了?有没有更好的方法来实现这个功能?

Shouldn't ComponentWillReceiveProps be fired in this case? since the props changed?. Is there a better way to implement this functionality?

handleSubmit (evt) {
    const {
        dispatch,
        login
    } = this.props;

    dispatch(actions.doLogin(value.login));
}

ComponentWillReceiveProps (nextprops) {
    const {
        login
    } = this.nextProps;

    if (login != null) {
        history.pushState({}, '/account');
    }
}

function mapStateToProps (state) {
    return {
        login: state.loginReducer.login
    }
}

export default connect(mapStateToProps)(Login);

推荐答案

如果 state.loginReducer.login 改变,那么 componentWillReceiveProps 将被触发.如果您认为您的 reducer 正在返回一个新状态,并且 componentWillReceiveProps 没有被触发,请确保新状态是不可变的.返回传递给 reducer 的相同状态引用将不起作用.

If state.loginReducer.login changes, then componentWillReceiveProps will get triggered. If you believe your reducer is returning a new state, and componentWillReceiveProps is not being triggered, make sure that the new state is immutable. Returning the same state reference thats passed to the reducer won't work.

来自 https://github.com/reactjs/redux/blob/master/docs/Troubleshooting.md

这是错误的:

function todos(state = [], action) {
  switch (action.type) {
  case 'ADD_TODO':
    // Wrong! This mutates state
    state.push({
      text: action.text,
      completed: false
    });
  case 'COMPLETE_TODO':
    // Wrong! This mutates state[action.index].
    state[action.index].completed = true;
  }

  return state;
}

这是对的:

function todos(state = [], action) {
  switch (action.type) {
  case 'ADD_TODO':
    // Return a new array
    return [...state, {
      text: action.text,
      completed: false
    }];
  case 'COMPLETE_TODO':
    // Return a new array
    return [
      ...state.slice(0, action.index),
      // Copy the object before mutating
      Object.assign({}, state[action.index], {
        completed: true
      }),
      ...state.slice(action.index + 1)
    ];
  default:
    return state;
  }
}

这篇关于更新 Redux 状态不会触发 componentWillReceiveProps的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆