javascript - React.js 终极版 : unwanted change of redux store on input handling

标签 javascript reactjs redux react-redux

我使用 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/

相关文章:

reactjs - 单击子组件时隐藏父 react 组件

javascript - Formik 和 ReactJs : SetFieldValue from child to parent component

javascript - 表单验证 JavaScript 数字总是返回 false

javascript - 如何使用 AJAX 通过 POST 发送图像?

javascript - Css:如何用边框线连接两个点

node.js - Gmail 式的收藏夹/星级功能的大致架构是怎样的?

reactjs - Material UI - 响应式抽屉

javascript - 如何从redux持久存储(localstorage)中读取

javascript - 如何强制执行 redux Action 只派发一次?

javascript - 如何在 Redux 中创建 Dynamic Reducer