Reputation: 1390
I am trying to create a sample app using React Native & Redux. What I am not able to understand is that why my state object is getting wrapped into another object.
I have initial state as {email: 'test'}. I have to access email as this.props.email.email Why do I have to do this.props.email.email instead of this.props.email
Any help will be appreciated.
Welcome.js
class Welcome extends Component {
render() {
return (
<View style={ styles.container }>
<View style = { styles.inputContainer }>
<Text>{JSON.stringify(this.props.email)}</Text>
<Button title = 'Update Email'
style = { styles.placeButton }
onPress={() => this.props.onChangeEmail('hello')}
/>
</View>
</View>
);
}
}
const mapStateToProps = state => {
return {
email: state.email
}
}
const mapDispatchToProps = dispatch => {
return {
onChangeEmail: (email) => { dispatch({type: 'CHANGE_EMAIL_INPUT', email: email}) }
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Welcome)
EmailReducer.js
const initialState = {
email: 'test',
};
const emailReducer = (state = initialState, action) => {
switch(action.type) {
case 'CHANGE_EMAIL_INPUT':
return Object.assign({}, state,
{ email: action.email }
);
default:
return state;
}
}
export default emailReducer;
Store.js
import { createStore, combineReducers } from 'redux';
import emailReducer from '../reducers/EmailReducer';
const rootReducer = combineReducers({
email: emailReducer
});
const configureStore = () => {
return createStore(rootReducer);
}
export default configureStore;
Upvotes: 1
Views: 438
Reputation: 456
When you call combineReducers you are creating a store with the following shape
{
email: {
email: 'test'
}
}
That is, the keys in the object passed to combineReducers are the root keys of the state object. The initial state for the email reducer is inserted in the key "email" of the state object.
This is the reason why you need to write this.props.email.email: the former is the key in the root state object (that deduced from combineReducers), the latter is the prop of the state part managed by emailReducer
Upvotes: 1