Reputation: 5095
I am new in react redux.
i have implement like:
Store :
import { createStore } from "redux";
const initialState = {
layersFlag : {
baseDistrictADhabi: "none",
baseDistrictAAin: "none"
}
};
const reducer = (state = initialState, action)=>{
switch (action.type) {
case "layerChange":
return Object.assign({}, state, {
...state,
layersFlag : {
baseDistrictADhabi: action.payload.baseDistrictADhabi,
baseDistrictAAin: action.payload.baseDistrictAAin
}
})
default:
return state;
}
}
const Store = createStore(reducer, initialState);
export default Store;
HomeScreen:
<Text> {this.props.baseDistrictADhabi} </Text>
<Text> {this.props.baseDistrictAAin} </Text>
const mapStateToProps = function(state) {
return {
baseDistrictADhabi: state.layersFlag.baseDistrictADhabi,
baseDistrictAAin: state.layersFlag.baseDistrictAAin
}
}
export default connect(mapStateToProps)(HomeScreen);
It is working but problem is when I am changing baseDistrictADhabi state then baseDistrictAAin(undefined) get reset.
Upvotes: 1
Views: 85
Reputation: 1397
If your action is only returning the value you want to update, you can just spread it into the layersFlag object.
Change your reducer to the following:
case "layerChange":
return {
...state,
layersFlag : {
...state.layersFlag,
...action.payload
}
}
This will keep all previous keys in your layersFlag object as they are, and only update the one that is returned in the action.
Upvotes: 3