将更新的子状态更新为父状态

时间:2017-10-26 01:27:51

标签: javascript reactjs ecmascript-6

我正在尝试获取父组件以从子组件中检索一些信息。具体来说,让父组件检索子项的当前状态。当我尝试下面的方法,并尝试呈现更新的父级时,更新速度变慢。在片段中,它只是向我返回一个简单的脚本错误。有没有比我当前的方法更好的方法来检索componentWillUpdate上的子状态?谢谢!

class Parent extends React.Component {
   constructor(props) {
    super();
    this.state = {
      parentState: "default",
    }
    this.getChildState = this.getChildState.bind(this);
  }
  
  getChildState(childState) {
    this.setState({
      parentState: childState
    })
  }

  render() {
    return (
      <div>
        <h2>current parentState: {this.state.parentState}</h2>
        <Child getChildState={this.getChildState} />
      </div>
    );
  }
}

class Child extends React.Component {
  constructor() {
    super();
    this.state = {
      onClick: 0,
    }
    this.handleClick = this.handleClick.bind(this);
  }
  
  handleClick() {
    this.setState({
      onClick: this.state.onClick + 1
    })
  }
  
  componentWillUpdate(nextProps, nextState) {
    nextProps.getChildState(nextState.onClick);
  }

 render() {
    return (
      <div>
      <h2>current childState: {this.state.onClick}</h2>
      <button onClick={this.handleClick}>Click Me</button>
      </div>
    );
  }   
}



ReactDOM.render(<Parent />, app);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="app"></div>

1 个答案:

答案 0 :(得分:1)

要更新父级的状态,当子级状态更新时,您应该使用带有以下签名的//Save data public void saveData() { int id = 0; String name, date_of_birth, mobile, age, next_birthday; Bitmap profilePicture; //Get data from user date_of_birth = tv_DoB.getText().toString(); name = et_name.getText().toString(); mobile = et_mobile.getText().toString(); profilePicture = iv_profile_image.getDrawingCache(); age = final_year + "years old"; next_birthday = remaining_months + "months" + remaining_days + "days"; Person person = new Person(id, name, date_of_birth, mobile, age, next_birthday); Toast.makeText(getContext(), person.toString(), Toast.LENGTH_LONG).show(); databaseHelper = new DatabaseHelper(getContext(), "person_database", null, 1); long inserted = databaseHelper.insertPerson(person); if (inserted >= 0) { Toast.makeText(getContext(), "Data inserted successfully...", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getContext(), "Data insertion failed...", Toast.LENGTH_SHORT).show(); } } 方法:

setState

子组件的setState(updater, [callback]) 函数应如下所示:

handleClick

当子状态更新时,这将调用handleClick() { this.setState({ onClick: this.state.onClick + 1 },()=>this.props.getChildState(this.state.onClick)); } 函数。

有关setState的更多信息,您可以查看React docs