【发布时间】:2020-06-22 17:51:08
【问题描述】:
我最近一直在努力使用 redux,因为它通常不会让我的 React 组件重新渲染。我知道我必须改变状态才能让 redux 知道我的状态发生了变化。但是由于某种原因,我的 Redux 仍然没有触发我的 React 组件上的 componentDidUpdate() 函数。 这是我的 reducer 函数的代码:
case ADD_OR_UPDATE_EVENT_OF_MATCH: {
const matches = [...state.matches];
const foundMatch = matches.find((match) => match.matchId === action.matchId);
const foundMatchIndex = matches.findIndex((match) => match.matchId === action.matchId);
if (!foundMatch) return state;
if (foundMatch.events) {
const foundEventIndex = foundMatch.events?.findIndex((event) => event.eventId === action.event.eventId);
if (foundEventIndex === -1) {
foundMatch.events?.push(action.event);
} else {
foundMatch.events[foundEventIndex] = action.event;
}
} else {
foundMatch.events = [action.event];
}
matches[foundMatchIndex] = foundMatch;
if (state.currentMatch) {
if (foundMatch.matchId === state.currentMatch.matchId) {
return {
...state,
currentMatch: foundMatch,
matches: matches
};
} else {
return {
...state,
matches: matches
};
}
}
return state;
}
【问题讨论】:
-
如果可能的话,你能分享你在codesandbox上添加完整的代码吗[codesandbox.io/]?它并不总是减速器有问题。有时代码明智的实现是错误的
-
@ShubhamVerma 这是我正在为我的公司工作的一个巨大项目,因此我不能分享比这更多的代码。但我所检查的是,如果在减速器之后我的使用状态的 React 组件调用 componentDidUpdate() 方法,但它没有。但是相同状态的其他突变调用 componentDidUpdate() 方法。所以我的建议是我的减速器做错了。也许是因为使用了扩展运算符?也许 Redux 没有注意到状态发生了变化或其他什么?
-
@ShubhamVerma 看来,当我在调试减速器时,Redux 的 hasChanged 值是真的,所以你是对的,我的错误似乎有所不同。真的很奇怪我的 componentDidUpdate 没有拍摄...
标签: javascript reactjs redux