为什么要分配这样的变量?

问题描述:

我甚至不知道这个名字,因此标题。为什么要分配这样的变量?

我基本上是要么加载通过道具(编辑)传递的数据或加载一个空的struct初始化我的模式窗体(创建新条目):

defaultStruct: { 
    text: null, 
    active: true, 
    options: [ 
     { 
      text: null, 
      correct: true, 
      position: 0, 
      _destroy: false, 
     } 
    ] 
}, 
getInitialState() { 
    return { 
     question: this.props.initialQuestion == null ? this.defaultStruct : this.props.initialQuestion, 
    }; 
} 

的主要思想是使用重置表单提交表单后,再次调用this.defaultStruct。

但是,当我在提交后执行console.log(this.defaultStruct)时,我可以看到它实际上已经从窗体状态填充了数据。所以...到底是什么。

handleSubmit(e){ 
    if(e){e.preventDefault();} 
    $.ajax({ 
     url: this.state.question.id == null ? this.props.applicationData.routes.questionsCreate : this.props.applicationData.routes.questionsUpdate, 
     dataType: 'json', 
     contentType: 'application/json', 
     type: 'POST', 
     data: this.digestDataForStupidRails('question', 'options'), 
     success: function(data) { 
      console.log(this.defaultStruct) 
     }.bind(this), 
     error: function(xhr, status, err) { 

     }.bind(this) 
    }); 
} 

控制台输出:

{ 
    "question": { 
     "text": "preg 1", 
     "active": true, 
     "options": [ 
      { 
       "text": "preg 1 a 1", 
       "correct": false, 
       "position": 0, 
       "_destroy": false 
      }, 
      { 
       "text": "preg 1 a 2", 
       "correct": true, 
       "position": 1, 
       "_destroy": false 
      } 
     ] 
    } 
} 

当然,我可以用一个函数,而不是解决这个问题,并使其每次返回一个空的结构,但是这让我好奇不过。

有人可以解释这种行为吗?

这不是特定于React,它是如何JavaScript(或基本上任何类似的语言)的作品。 defaultStruct是一个对象,因此它通过引用传递,而不是作为新副本传递。如果你想保留getInitialState,你应该找到一种方法clone the object,或者根据喜欢的答案中的建议或使用已具有此功能的库,例如lodashunderscore或类似的。或者,由于您已经在使用jQuery,因此您可以使用$.extend,正如第一个链接的第二个答案中回答的那样。

+0

哦,现在我对JavaScript有了更多的了解,谢谢! –