2017-05-03 28 views
1

我在reactjs代碼中遇到了這個問題,但它更像是我理解javascript鍵/值數組如何工作的問題。我如何讓密鑰在下面的例子中動態傳遞?Reactjs設置狀態動態關鍵字Javascript

問題的細節在done()函數中。任何語法錯誤都是因爲我在Intranet上工作,必須手工輸入所有內容。正如在done()函數中提到的那樣,如果我對密鑰進行了硬編碼,一切都可以正常工作,但我當然不希望這樣做。我已經嘗試了和沒有引號周圍的關鍵。

class Container extends React.Component { 
     constructor(props){ 
     super(props) 
     this.state = { 'abc': {} 
     } 

     this.retrieveDataFromTo = this.retrieveDataFromTo.bind(this) 
     } 

     retrieveDataFromTo(url, storeKey){ 
     $.ajax({ 
      method: 'GET', 
      url:url, 
      dataType: 'json' 
     }) 
     .done(response => { 
      this.setState({storeKey: response}) 
      //everything works if i do this instead of the above line... 
      //this.setState({'abc': response}) 
      //which proves the only problem is the storeKey being "dynamic" 
      //so how do i get the store key to work "dynamically" here? 
     }) 
     .fail(ajaxError) 
     } 

     componentDidMount(){ 
     this.retreiveDataFromTo('abc/getData', 'abc') 
     } 

     ... 

    } 

回答

0

你可以做這樣的事情:

this.setState(function(prevState){ 
    prevState[storeKey] = response; 
    return prevState; 
})) 

或動態密鑰與ES6

setState({ [storeKey]: response }); 
1

ES6中的動態鍵JavaScript通常用括號括起來,表示存儲要更改的鍵值的變量。所以你的情況,你會想做的事:

setState({ [storeKey]: response }); 

More on dynamic keys in JS