如何在 Redux Toolkit 减速器中替换整个状态? [英] How can you replace entire state in Redux Toolkit reducer?

查看:42
本文介绍了如何在 Redux Toolkit 减速器中替换整个状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

解决方案是在我完全替换后返回state(return state = {...action.payload})!但为什么?单独替换字段时不需要返回.

The solution is to return state after I replace it completely (return state = {...action.payload})! But why? I don't need to return it when I replace the fields individually.

我正在使用 Redux Toolkit,它简化了一些 Redux 样板.他们做的一件事是使用 Immer 允许您直接修改"状态(实际上,您不是).它工作正常,除了我不知道如何完全替换我的状态部分.例如,我想做这样的事情

I'm working with the Redux Toolkit, which simplifies some Redux boilerplate. One thing they do is use Immer to allow you to directly 'modify' state (in fact, you're not). It works fine, except I don't know how to replace my section of state entirely. For instance, I want to do something like this

const reducer = createReducer({ s: '', blip: [] }, {

    [postsBogus.type]: (state, action) => {
        state = { ...action.payload };
    }

state 保持不变.相反,我必须这样做

but state remains untouched. Instead I have to do this

[postsBogus.type]: (state, action) => {
    state.s = action.payload.s;
    state.blip = action.payload.blip;
}

有没有办法完全替换状态?

Is there a way I can replace state entirely?

推荐答案

是的,正如您所指出的,您必须返回一个新值才能完全替换状态.

Yes, as you noted, you must return a new value to replace the state entirely.

即使在平原"中Redux 减速器,分配 state = newValue 什么都不做,因为所做的只是说明名为 state局部函数变量现在指向了一个不同的内存中的值.这不会返回一个新值.

Even in a "plain" Redux reducer, assigning state = newValue does nothing, because all that does is say that the local function variable named state is now pointing to a different value in memory. That does nothing to return a new value.

特别是对于 Immer,您可以改变代理的内容-包装 state 值,只要它是一个对象或数组,或者您可以返回一个全新的值,但不能同时返回两个值.

For Immer specifically, you can either mutate the contents of the Proxy-wrapped state value as long as it's an object or array, or you can return an entirely new value, but not both at once.

这篇关于如何在 Redux Toolkit 减速器中替换整个状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆