我的减速器已执行但状态不会在反应中更新
my reducer is executed but state does not update in react
我正在为我的项目使用 recat redux,在一个组件中我需要更新我的状态,但由于我正在处理异步调用,我需要在我的 componentDidUpdate 中执行如下操作调用:
componentDidUpdate() {
this.props.updateHamburgerMenu(this.props.Channel.channelIdArr);
}
这是我的操作:
export function updateHamburgerMenu(channelIdArr) {
return dispatch => {
dispatch(
{
type: "UPDATE_HAMBURGER_MENU",
payload: {
"channelIdArr":channelIdArr
}
}
);
};
}
在我的减速器中我有:
switch (action.type) {
case "UPDATE_HAMBURGER_MENU":
var channelList=state.allChannelList.slice();
channelList.unshift({
"id": channelIdArr[0],
"channelName": "sssssssss",
"status": "Inactive"
});
alert("reducer called");
state.allChannelList=channelList;
break;}
return state;
现在,当我 运行 它时,我可以看到警报正在运行,但状态根本没有更新。
我也尝试了另一种方法如下:
state={"channelsArr":state.channelsArr,"AllChannels":state.AllChannels,"channelIdArr":state.channelIdArr,"channelLabelForScrolls":[], "latestAction":action.type, "allChannelList":channelList};
break;
这样一来,state好像一直在更新,一直在无限循环。
真的很困惑,有人可以帮忙吗?我错过了什么?
更新:
当我在另一个减速器中分离 allChannelList 时,它起作用了。因此,似乎在 componentdidupdate 的特定情况下更新 allChannelList 会进入无限循环,并且状态会不断更新自身。但是我不知道为什么会这样
在你的 reducer case 语句中,你应该返回一个代表当前动作后状态的新对象 - 你似乎试图直接分配给传递的 allChannelList
属性在 state
个对象中。
即
return {
...state,
allChannelList: channelList
};
我正在为我的项目使用 recat redux,在一个组件中我需要更新我的状态,但由于我正在处理异步调用,我需要在我的 componentDidUpdate 中执行如下操作调用:
componentDidUpdate() {
this.props.updateHamburgerMenu(this.props.Channel.channelIdArr);
}
这是我的操作:
export function updateHamburgerMenu(channelIdArr) {
return dispatch => {
dispatch(
{
type: "UPDATE_HAMBURGER_MENU",
payload: {
"channelIdArr":channelIdArr
}
}
);
};
}
在我的减速器中我有:
switch (action.type) {
case "UPDATE_HAMBURGER_MENU":
var channelList=state.allChannelList.slice();
channelList.unshift({
"id": channelIdArr[0],
"channelName": "sssssssss",
"status": "Inactive"
});
alert("reducer called");
state.allChannelList=channelList;
break;}
return state;
现在,当我 运行 它时,我可以看到警报正在运行,但状态根本没有更新。
我也尝试了另一种方法如下:
state={"channelsArr":state.channelsArr,"AllChannels":state.AllChannels,"channelIdArr":state.channelIdArr,"channelLabelForScrolls":[], "latestAction":action.type, "allChannelList":channelList};
break;
这样一来,state好像一直在更新,一直在无限循环。 真的很困惑,有人可以帮忙吗?我错过了什么?
更新:
当我在另一个减速器中分离 allChannelList 时,它起作用了。因此,似乎在 componentdidupdate 的特定情况下更新 allChannelList 会进入无限循环,并且状态会不断更新自身。但是我不知道为什么会这样
在你的 reducer case 语句中,你应该返回一个代表当前动作后状态的新对象 - 你似乎试图直接分配给传递的 allChannelList
属性在 state
个对象中。
即
return {
...state,
allChannelList: channelList
};