简体   繁体   English

ReactJS动态更新状态

[英]ReactJS update state dynamically

I'm trying to update a components state dynamically based on the arguments sent on a callback function. 我正在尝试根据在回调函数上发送的参数动态更新组件状态。

So, the goal is if the component sends valueChange('id', 1) ... this.state.contractLine.id will be updated to 1 and if the component sends valueChange('innerLevel.name', 'newName') this.state.contractLine.innerLevel.name will be updated to newName 因此,目标是如果组件发送valueChange('id', 1) ... this.state.contractLine.id将更新为1并且如果组件发送valueChange('innerLevel.name', 'newName') this.state.contractLine.innerLevel.name将更新为newName

This is the code i'm using (but it's not working like expected). 这是我正在使用的代码(但无法正常工作)。

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);
}

Any ideas? 有任何想法吗?

EDIT --SOLVED-- 编辑-解决-

Just in case someone has the same problem... I followed @rauliyohmc advice and managed to solve the problem with lodash . 以防万一有人遇到相同的问题...我遵循@rauliyohmc建议并设法用lodash解决了问题。 The code used (much simpler than I ever thought) was: 使用的代码(比我想象的要简单得多)是:

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

    _.set(newState, statePath, inputValue);

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

Just in case someone has the same problem... I followed @rauliyohmc advice and managed to solve the problem with lodash. 以防万一有人遇到相同的问题...我遵循@rauliyohmc的建议并设法用lodash解决了问题。 The code used (much simpler than I ever thought) was: 使用的代码(比我想象的要简单得多)是:

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

    _.set(newState, statePath, inputValue);

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM