以编程方式生成的反应状态键名称

时间:2016-11-27 19:36:35

标签: reactjs

在ReactJS中将变量键名称传递给setState的正确方法是什么?我发现自己不得不玩临时地图游戏,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);
}

它有效,但我宁愿在每次修改时调用setState,而不是预先构建地图,特别是在我只有一次修改的情况下。

1 个答案:

答案 0 :(得分:0)

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

但我认为以下是您需要的,您可以在[...]

中编写变量名称
    this.setState({
    [arraySizeKey]: lookupCount - 1,
    [this.composeKeys(lookupPrefix, Editor.isDeletedKey)]:true  
    });