简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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