2017-09-07 36 views
0

我正嘗試在componentsDidMount/componentsWillMount中調用addRow函數,但狀態的非狀態在addRow上得到更新。 我想加載onload事件中的行。我對React相當陌生。非常感謝任何提示。在componentDidMount或componentWillMount中未更新的狀態 - React js

componentDidMount(){ 
    let users = X.users; 
    for (let i = 0; i < users.length; i++) { 
    this.addRow(); 
    }; 
} 

addRow() { 
    this.setState({testState : "I am updated"}); 
    console.log("State : "+ this.state.testState); 
    const inputList = this.state.inputList; 
    const index = this.state.index; 
    let rows = this.state.rows; 
    const row = (
    <tr key={ inputList.length } name={ inputList.length }> 
     <td><input name={'phone_'+index} type="number" placeholder="Phone Number" pattern="[0-9]*" inputMode="numeric" ref={inp => this[`phone_${index}`] = inp} key={index} onBlur={(e) => this.validateInput(e, false)}/> </td> 
     <td><input name={'fwd_'+index} type="number" placeholder="Foward Phone Number" pattern="[0-9]*" inputMode="numeric" ref={inp => this[`fwd_${index}`] = inp} key={index} onBlur={(e) => this.validateInput(e, true)}/></td> 
     <td id="second-last-child"> 
     <ButtonGroup> 
      <OverlayTrigger placement="top" overlay={<Tooltip id="tooltip">Remove</Tooltip>}> 
      <Button className="config-button" onClick={() => this.removeRow(inputList.length)}><Glyphicon glyph="remove"></Glyphicon></Button> 
      </OverlayTrigger> 

      <OverlayTrigger placement="top" overlay={<Tooltip id="tooltip">Save</Tooltip>}> 
      <Button className="config-button"><Glyphicon glyph="saved" onClick={ this.handleSubmit }></Glyphicon></Button> 
      </OverlayTrigger> 

      <OverlayTrigger placement="top" overlay={<Tooltip id="tooltip">Forward</Tooltip>}> 
      <Button className="config-button"><Glyphicon glyph="forward" onClick={ this.addCallFWDNum }></Glyphicon></Button> 
      </OverlayTrigger> 
     </ButtonGroup> 
    </td> 
    <td id="forwarded-indicator"> 
    <label className="switch"> 
     <input className="activate-checkbox" type="checkbox" value={this.state.isChecked} onChange={this.toggleChange} ref={inp => this[`isAct_${index}`] = inp} key={index} /> 
     <span className="slider"></span> 
    </label> 
    </td> 
    </tr> 
); 
    console.log(index); 
    rows.push(row); 

    this.setState({ 
    inputList: inputList.concat(row) 
    }); 
    this.setState({ 
    index: index+1 
    }); 
}, 

控制檯日誌:

State : 
0 
0 
users.length : 9 

回答

1

陣營的setState功能是異步的。這意味着當你調用這個函數時,它可能不會馬上運行。所以在addRow()的第二行,你會發現這個狀態還沒有真正改變。

如果你想等待狀態運行一些代碼之前更新,使用可選的回調參數在setState(),像這樣:

addRow() { 
    this.setState({ testState: 'test' },() => { 
    console.log("state updated:", this.state) 
    // State is updated in this function 
    }) 

    console.log("state probably not updated:", this.state) 
    // State may not have updated yet 
} 

你必須使用一個箭頭功能() => {}(像我的例子)或.bind(this)以確保this仍然在回調函數中引用您的類。

+0

謝謝悉尼!另外我做了一些非常愚蠢的事情 - 而不是添加所有行,我只有concat行;) – Newbie

相關問題