gpt4 book ai didi

javascript - 如何在 createSlice 的 reducer 中获取状态值?

转载 作者:行者123 更新时间:2023-12-03 07:04:55 26 4
gpt4 key购买 nike

我在我的 react 项目中使用 redux-toolkit。在 createSlice 的化简器中,我想使用状态中现有的实体数组并附加新数组,然后再减少最终状态。但我无法获得状态值。
这是 reducer 代码

export const usersSlice = createSlice({
name: "users",
initialState: initialUsersState,
reducers: {
usersCreated: (state: UsersState, action) => {
// in real, return count from the server and append the entities on front-end only?
const { count, entities } = action.payload;
const existingEntities = state.entities;
const newEntities = [...existingEntities, ...entities];
const totalCount = state.totalCount+count;
return {
...state,
entities: newEntities,
totalCount: totalCount,
listLoading: false,
error: null,
};
},
}});

当我调试 state.entites 变量时,它看起来像这样
enter image description here
有没有办法访问 reducer/extraReducer 中的当前状态值以根据需要重新创建状态?
因为我认为在 reducer 之外直接使用状态值是一种不好的做法。请指导我,如果我错了。
编辑
code sandbox @Linda Paiste 创建的工作正常,这意味着我们可以访问 reducer 中的状态变量,但我们无法调试状态变量以更深入地挖掘状态变量目前持有的内容,因为 Redux-toolkit 正在处理状态以它自己的方式...
从调试屏幕截图中可以明显看出
enter image description here

最佳答案

总结我自己和@karlmaxlopez 评论中的信息:
我将您的代码复制到 CodeSandbox demo 中,发现代码 确实按预期执行了 。即使在检查时 state.entities 的值显示为 state.entities 或记录时显示为 Proxy ,您也可以将其附加到 null 数组,就像它是一个普通数组一样。
这是因为 redux-toolkit 使用 Immer 来防止你直接改变状态。在普通的 redux reducer 中,您会收到之前的 state 作为函数参数。作为用户,您有责任不对其进行变异,而是通过使用非变异方法(例如对象扩展、数组连接等)返回具有更新值的新对象。这就是您在 usersCreated reducer 中所做的,这完全没问题。
但是 redux-toolkit 和 Immer 为如何编写 reducer 开辟了额外的可能性。在 Immer reducer 中,函数接收的 state 参数是“草稿”对象。这意味着您可以直接改变草稿对象而不会引起任何问题,因为它只是草稿而不是真正的 state
这也意味着当你试图检查这个先前的状态时,它的行为会很奇怪,因为它只是一个草稿,而不是你所期望的实际对象。
如果你想要 console.log 一个草稿值,你可以通过使用 immer console.log(current(value)) 函数调用 current 来实现,该函数包含在 redux 工具包中。 (根据@markerikson 的评论编辑)。
至于检查每个操作对您的状态所做的更改,我建议使用 Redux DevTools 。我能够看到发送了哪些操作、当前状态、进行了哪些更改等。
Redux DevTools screenshot

关于javascript - 如何在 createSlice 的 reducer 中获取状态值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63885139/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com