【问题标题】:ReactJS update state dynamicallyReactJS 动态更新状态
【发布时间】:2017-04-11 14:50:20
【问题描述】:

我正在尝试根据回调函数上发送的参数动态更新组件状态。

因此,目标是如果组件发送valueChange('id', 1)...this.state.contractLine.id 将更新为1,如果组件发送valueChange('innerLevel.name', 'newName') this.state.contractLine.innerLevel.name 将更新为newName

这是我正在使用的代码(但它没有像预期的那样工作)。

valueChange(statePath, inputValue) {
    var newState = this.state; 

    var stateBeingChanged = this.state['contractLine'];

    var pathList = statePath.split('.');
        for (var i = 0; i < pathList.length; i++) {
            var elem = pathList[i];
            stateBeingChanged = stateBeingChanged[elem];
        }

    stateBeingChanged = inputValue;

    newState['contractLine'] = stateBeingChanged;

    this.setState(newState);
}

有什么想法吗?

编辑--已解决--

以防万一有人遇到同样的问题... 我听从了@rauliyohmc 的建议,并设法用lodash 解决了这个问题。 使用的代码(比我想象的要简单得多)是:

valueChange(statePath, inputValue) {
    var newState = Object.assign({}, this.state['contractLine']);

    _.set(newState, statePath, inputValue);

    this.setState({contractLine: newState});
}

【问题讨论】:

  • 快速查看您的代码,您似乎正在改变状态。罪魁祸首是var newState = this.state,它具有将newState 指向同一个对象引用的效果。因此,当您执行newState['contractLine'] = stateBeingChanged 时,您正在变异this.state。而是在生成新对象之前执行var newState = Object.assign({}, this.state)。让我知道这是否有帮助

标签: javascript reactjs dynamic state


【解决方案1】:

以防万一有人遇到同样的问题……我听从了@rauliyohmc 的建议,并设法用 lodash 解决了这个问题。使用的代码(比我想象的要简单得多)是:

valueChange(statePath, inputValue) {
    var newState = Object.assign({}, this.state['contractLine']);

    _.set(newState, statePath, inputValue);

    this.setState({contractLine: newState});
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-30
    • 1970-01-01
    • 1970-01-01
    • 2021-01-27
    • 2018-07-25
    • 2014-09-20
    • 2020-11-03
    • 1970-01-01
    相关资源
    最近更新 更多