[英]Redux reducer does not force a rerender on my React Component although I mutated the state
I have been struggling with redux lately because it often does not let my React Components rerender.我最近一直在为 redux 苦苦挣扎,因为它通常不会让我的 React 组件重新渲染。 I know that I have to mutate the state in order to let redux know that my state changed.
我知道我必须改变 state 才能让 redux 知道我的 state 发生了变化。 But for some reason, my Redux still doesn't trigger the componentDidUpdate() function on my React Component.
但是由于某种原因,我的 Redux 仍然没有触发我的 React 组件上的 componentDidUpdate() function。 Here is the code for my reducer function:
这是我的减速器 function 的代码:
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;
}
I'm afraid this statement is very wrong:恐怕这种说法是非常错误的:
I know that I have to mutate the state in order to let redux know that my state changed.
我知道我必须改变 state 才能让 redux 知道我的 state 发生了变化。
The exact opposite is true.恰恰相反。 You should never actually mutate Redux state!
您永远不应该真正改变 Redux 状态!
Lines like this are mutating, and are therefore breaking your app:像这样的行正在发生变化,因此会破坏您的应用程序:
foundMatch.events[foundEventIndex] = action.event;
You need to change this logic to all be immutable updates , instead.相反,您需要将此逻辑更改为所有不可变更新。
You should also probably look at using our official Redux Toolkit package to write your Redux logic, as it does allow you to write "mutating" logic in reducers that gets turned into safe and correct immutable updates internally.您还应该考虑使用我们的官方 Redux 工具包 package来编写您的 Redux 逻辑,因为它允许您在内部编写“和更正不可变”的逻辑,从而在 reducers 中编写“和更正”的安全更新。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.