更新具有对象数组的减速器中的 redux 状态 [英] Update the redux state in the reducer having array of objects
问题描述
我是 react-redux 的新手.
I am new to the react-redux.
我确实有一个像,
const initialState = {
Low: [
{
id: 0,
technologyId: 0,
technology: '',
level: 'EASY'
}
],
Medium: [
{
id: 0,
technologyId: 0,
technology: '',
level: 'MEDIUM'
}
],
High: [
{
id: 0,
technologyId: 0,
technology: '',
level: 'TOUGH'
}
]
}
Now,
export default function QuizData(state = initialState, action) {
switch (action.type) {
case QUIZ_DATA:
return {
...state,
Low: action.data,
error: false,
}
case RESET_SETUP_QUIZ: {
console.log("intial state is ", ...state);
return {
...state
}
现在,这里发生的是在一些操作之后,这个对象随着每个键都有一些值而发生变化.喜欢,
Now, here what happens is after some manipulations, this objects gets changes with every key is having some values. like,
{
Low: [
{
id: 0,
technologyId: 11,
technology: 'xsxs',
level: 'EASY'
}
],
Medium: [
{
id: 0,
technologyId: 22,
technology: 'swwsw',
level: 'MEDIUM'
}
],
High: [
{
id: 0,
technologyId: 110,
technology: 'xsxsx',
level: 'TOUGH'
}
]
}
所以,这被改变了.现在,我想做的是,
So, This gets changed.Now, what I want to do is that ,
当用户点击按钮时,我想将其更改为初始状态.
When user clicks a button that time I want to change this to the initial state.
这样它就不会有任何值,因为它应该与默认值相同.
So that it will not have any values as it should be same as by default.
所以,我尝试了什么
return {
initalState
}
但在这里,初始状态也具有相同的值.
But here, initial state is also having the same values.
所以,我没有办法让它达到初始水平.
So, I am not getting a way to make it to the initial level.
有人可以帮我吗?
推荐答案
因为您使用原始状态对象并返回它的修改版本(即您确实影响了您的 initialState).
Because you use the original state object and return a modified version of it (i.e. you do affect your initialState).
你必须在你的reducer中创建一份状态的副本,例如
You must create a copy of the state in your reducer, for example
case QUIZ_DATA:
return Object.assign(
{},
state,
{
Low: action.data,
error: false
}
)
case RESET_SETUP_QUIZ: {
return Object.assign(
{},
state
)
}
你有像 immutablejs 这样的专用库来处理这个问题(https://redux.js.org/recipes/usingimmutablejs)
You have dedicated librairies like immutablejs to handle this (https://redux.js.org/recipes/usingimmutablejs)
这篇关于更新具有对象数组的减速器中的 redux 状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!