2017-05-03 33 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