2016-11-27 75 views
0

在ReactJS中將可變鍵名稱傳遞給setState的正確方法是什麼?我發現自己不得不扮演臨時地圖的遊戲,一拉以編程方式生成的反應狀態鍵名稱

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每個修改,而不是建立在地圖的前期,尤其是在情況下,我只有一個這樣的修改。

回答

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

,使密鑰字符串數組,而不是字符串。注意到:地圖。 – kolosy