This question already has an answer here:
- What do these three dots in React do? 16 answers
I am learning Redux, React and ES6. I already developed with JS, but this new world of ES6 are surprising me with a lot of new things like "=>" to declare arrow functions and other. However, in this new Redux studies, I confront with ...
in middle of my code.
Bellow I have an example:
import { combineReducers, createStore } from 'redux'
const userReducer = (state={}, action) => {
switch(action.type) {
case 'CHANGE_NAME':
state = {...state, name: action.payload};
break;
case 'CHANGE_AGE':
state = {...state, age: action.payload};
break;
}
return state;
};
const tweetsReducer = (state=[], action) => {
return state;
};
const reducers = combineReducers ({
user: userReducer,
tweetsReducer: tweetsReducer,
});
const store = createStore(reducers);
store.subscribe(() =>
console.log('The chage was: ', store.getState())
);
store.dispatch({type: 'CHANGE_NAME', payload: 'Will'})
store.dispatch({type: 'CHANGE_AGE', payload: 21});
If I replace
state = {...state, name: action.payload};
and
state = {...state, age: action.payload};
with
state.name = action.payload;
and
state.age = action.payload;
it works, but the age was inserted into object together name and in first case the name was inserted and after age was inserted.
Why does it happen? How can I use ...
in my future codes? Is it just in related with states?