【问题标题】:Redux reducer does not force a rerender on my React Component although I mutated the stateRedux reducer 不会强制我的 React 组件重新渲染,尽管我改变了状态
【发布时间】: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


【解决方案1】:

恐怕这种说法是非常错误的:

我知道我必须改变状态才能让 redux 知道我的状态发生了变化。

恰恰相反。 你不应该永远真正改变 Redux 状态!

这样的行会发生变化,因此会破坏您的应用程序:

foundMatch.events[foundEventIndex] = action.event;

您需要将此逻辑更改为全部为immutable updates

您还应该考虑使用our official Redux Toolkit package 来编写您的 Redux 逻辑,因为它确实允许您在 reducer 中编写“变异”逻辑,从而在内部转换为安全且正确的不可变更新。

【讨论】:

    猜你喜欢
    • 2021-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-20
    • 1970-01-01
    • 2021-03-27
    • 2018-12-31
    • 2020-01-30
    相关资源
    最近更新 更多