Answer the question
In order to leave comments, you need to log in
React/Redux reducer work?
As they say in the tutorials, the data in the reducers should not be mutated, but should be replaced.
Suppose we have a reducer that stores an array of Users, i.e. state is [ ], each user has a set of properties.
There are several actions in the reducer, add, remove, change a property.
1. We want to add a new user. How to do it right:
a. Take the state array, add a new element to it and return state.
b. Clone the state, add a new element to it already and return this state.
in. Another variant.
2. We want to change the username. How to do it right:
a. We find this user in the state, clone the user object, change the property of the new object, replace the old object in the state with the new one, return the state.
b. We just find the user in the state array, assign a new value to the property, clone the entire state and return it already.
in. Another variant.
Answer the question
In order to leave comments, you need to log in
If without immutablejs, then:
1.
return {
...state,
items: [
...state.items,
action.payload,
],
return {
...state,
items: state.items.map((item) => {
if (item.id === action.payload.id) {
return {
...item,
name: action.payload.name,
};
}
return item;
}),
};
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question