未在componentDidMount或componentWillMount中更新的状态 - React js

时间:2017-09-07 00:01:47

标签: javascript reactjs

我试图在componentsDidMount / componentsWillMount中调用addRow函数,但是在addRow上没有更新状态。 我试图在onload事件中加载行。我对React很新。非常感谢任何提示。

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 个答案:

答案 0 :(得分:1)

React的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仍然在回调函数中引用您的类。