问题描述:

What is the correct way to pass in a variable key name to setState in ReactJS? I'm finding myself having to play the temporary map game, a la

removeLookup(idx) {

let lookupPrefix = this.composeKeys(Editor.fooDefinition, "lookups");

let arraySizeKey = this.composeKeys(lookupPrefix, Editor.arrayLengthKey);

let lookupCount = this.state[arraySizeKey];

let newState = new Map();

newState[arraySizeKey] = lookupCount - 1;

newState[this.composeKeys(lookupPrefix, Editor.isDeletedKey)] = true;

this.setState(newState);

}

It works, but I'd rather just call setState with each modification, instead of building the map upfront, especially in cases where I only have one such modification.

网友答案:
You don't have to use map you acn use just an obj.

 var _state = {};
 _state[arraySizeKey] = lookupCount - 1;
 _state[this.composeKeys(lookupPrefix, Editor.isDeletedKey)] = true;
 this.setState(_state);

But i think below is what you need you can write variable name in [...]

    this.setState({
    [arraySizeKey]: lookupCount - 1,
    [this.composeKeys(lookupPrefix, Editor.isDeletedKey)]:true  
    });
相关阅读:
Top