问题
I am new to the react-redux.
I do have an object which is like,
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.
SO, what I tried it
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.
Can one help me with this ?
回答1:
Because you use the original state object and return a modified version of it (i.e. you do affect your initialState).
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
)
}
You have dedicated librairies like immutablejs to handle this (https://redux.js.org/recipes/usingimmutablejs)
来源:https://stackoverflow.com/questions/53648186/update-the-redux-state-in-the-reducer-having-array-of-objects