gpt4 book ai didi

redux - 更新 Redux 状态不会触发 componentWillReceiveProps

转载 作者:行者123 更新时间:2023-12-03 10:36:15 24 4
gpt4 key购买 nike

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

不应该ComponentWillReceiveProps在这种情况下被解雇?自从 Prop 变了?有没有更好的方法来实现这个功能?

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 的相同状态引用将不起作用。

来自 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 - 更新 Redux 状态不会触发 componentWillReceiveProps,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33322068/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com