Reputation: 11
I am trying to understand this React redux example on : https://codesandbox.io/s/f2ded
In reducer.js, the initial state is :
const initialState = {
taskName: "",
tasks: []
};
In App.js, we have :
const mapStateToProps = state => {
return {
...state.list
};
};
The state
does not have a property list
and it state.list
should be an empty object {}
. But, it actually holds
Appreciate any help in understanding how exactly this works. Thank you.
Upvotes: 0
Views: 86
Reputation: 13902
It's because of the combineReducers at the bottom
const reds = combineReducers({ list });
export default reds;
That means that everything in that part of the Redux state is state.list.taskName
or state.list.tasks
etc.
[edit] just wanted to add some clarity from the official docs, https://redux.js.org/api/combinereducers/
rootReducer = combineReducers({potato: potatoReducer, tomato: tomatoReducer})
// This would produce the following state object
{
potato: {
// ... potatoes, and other state managed by the potatoReducer ...
},
tomato: {
// ... tomatoes, and other state managed by the tomatoReducer, maybe some nice sauce? ...
}
}
Upvotes: 2
Reputation: 275
To understand it more deeply you need to learn about combineReducers
Example
rootReducer = combineReducers({potato: potatoReducer, tomato: tomatoReducer})
// This would produce the following state object
{
potato: {
// ... potatoes, and other state managed by the potatoReducer ...
},
tomato: {
// ... tomatoes, and other state managed by the tomatoReducer, maybe some nice
// sauce? ...
}
}
You can control state key names by using different keys for the reducers in the passed object. For example, you may call combineReducers({ todos: myTodosReducer, counter: myCounterReducer })
for the state shape to be { todos, counter }
.
A popular convention is to name reducers after the state slices they manage, so you can use ES6 property shorthand notation: combineReducers({ counter, todos })
. This is equivalent to writing combineReducers({ counter: counter, todos: todos })
.
So when you are using ...state.list
you are getting it because of combineReducers({ list: listReducer })
or simply combineReducers({ list})
To know more please follow: combineReducers
Upvotes: 0