我使用 mapStateToProps
将一些值从 redux store 映射到 props:
function mapStateToProps(state, ownProps) {
// state.layers has 3 Objects containing arrays
return {
layers: state.availableLayers.toObject()
};
}
我正在显示不同的图层,用户可以选择他/她想要创建的图层。在点击事件中,我将所选图层写入状态:
openParams(layer){
this.setState({
showLayer: layer
});
}
层的参数是从单击事件传递的,在该事件中我遍历了 this.props.layers
中所有可能的层。 .
现在我希望用户能够更改一些配置。为此,只要配置字段的输入发生变化,我就会有一个 handleInput 事件:
handleChange(e) {
let field = e.target.name;
let value = e.target.value;
let tmpLayer= this.state.showLayer;
tmpLayer[field]["value"] = value;
this.setState({ showLayer: tmpLayer });
}
当用户完成后,我调用 redux 操作:this.props.actions.createLayer(this.state.showLayer);
但是当我这样做时,商店不仅创建了图层。而且还更改了 redux 存储中的 state.availableLayers。但这些数据应该保持不变。我的 reducer 没有改变它,我已经检查过了。好像是 tmpLayer[field]["value"] = value;
行正在改变 redux 商店。但我不明白为什么?我的 this.state.showLayer
似乎有一些引用到 redux 商店?!我已经尝试在 mapStateToProps
上复制对象使用 immutable.js 和 Object.assign({}, state.availableLayer.toObject()
,但这没有帮助。
编辑:使用 JSON.parse(JSON.stringify(this.state.showLayer))
在 Object.assign({}, this.state.showLayer)
时解决了问题和 {...this.state.showLayer}
@mkatanski 建议不要。怎么样?
最佳答案
好的。有一个对商店的引用并更改需要深层复制,因为事先不知道 showLayer
的结构和字段,并且可能因图层类型而异。
在 handleChange()
函数中使用此 JSON.parse(JSON.stringify(this.state.showLayer))
或 JSON.parse(JSON
解决了这个问题。mapStateToProps()
中的 .stringify(state.availableLayers.toObject))
关于javascript - React.js 终极版 : unwanted change of redux store on input handling,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45732569/