我是React Redux的新手。
我有类似的工具:
商店:
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;
主屏幕:
<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);
它正在工作,但问题是当我更改baseDistrictADhabi状态时,baseDistrictAAin(未定义)将重置。
答案 0 :(得分:3)
如果您的操作仅返回要更新的值,则可以将其传播到layersFlag对象中。
将减速器更改为以下内容:
case "layerChange":
return {
...state,
layersFlag : {
...state.layersFlag,
...action.payload
}
}
这会将所有先前的键保留在您的layersFlag对象中,并且仅更新操作中返回的键。