在React中更新子组件状态

时间:2019-11-18 09:54:53

标签: reactjs

使用道具更新子组件的状态时遇到很多麻烦。

我有一个称为InputForm的父组件,该组件维护一个2d数组,当用户在表单中填写数据时,该数组将更新。这可以正常工作,但是,我试图使用此状态变量来更新子组件Matrix的状态。但是,我似乎没有做任何事情实际上可以改变Matrix组件的状态。

class InputForm extends Component {
  constructor(props) {
    super(props);
    this.matrix = React.createRef();
    this.state = {
      equation: null,
      integers: []
    };
  }

  addIntegers = v => {
    const newIntegers = this.state.integers.slice();
    newIntegers.push(v);
    this.setState({ integers: newIntegers });
    this.matrix.current.changeElements(this.state.integers);
  };

  render() {
    return (
      <div>
        <form onSubmit={this.mySubmitHandler}>
          <input
            type="text"
            name="equation"
            onChange={this.handleInputChange}
          />
        </form>
        <Matrix ref={this.matrix} values={this.state.integers} />
      </div>
    );
  }

class Matrix extends Component {
  state = {
    rows: 0,
    cols: 0,
    elements: [[]]
  };

  constructor(props) {
    super(props);
    this.setState({ elements: this.props.value });
  }

  changeElements = props => {
    this.setState({ elements: this.props.values });
    console.log(this.elements);
  };

2 个答案:

答案 0 :(得分:1)

在父组件中,您将值作为道具传递

<Matrix ref={this.matrix} values={this.state.integers} />

在“矩阵”中,您正在访问:

constructor(props) {
    super(props);
    this.setState({ elements: this.props.value });
  }

this.props.value不在的地方,您应该访问this.props.values

答案 1 :(得分:0)

因为this.setState (...)是异步函数。如果要在更新父状态后调用this.matrix.current.changeElements(this.state.integers);函数,请将this.setState (...)的第二个参数设置为回调函数。

这是固定代码

class InputForm extends Component {
...
  addIntegers = v => {
    const newIntegers = this.state.integers.slice();
    newIntegers.push(v);
    this.setState({ integers: newIntegers }, () => {     // use callback
        this.matrix.current.changeElements(this.state.integers);
    });
  };
...
class Matrix extends Component {
  constructor(props) {
    super(props);
    this.state = {
       rows: 0,
       cols: 0,
       elements: this.props.value || [[]] // try like this.
    };
  }

  changeElements = props => {
    // this.setState({ elements: this.props.values }); // wrong
    this.setState({ elements: props.values }, () => {
       console.log(this.state.elements);
    }); // maybe like this
  };

这是一个简单的示例。

class App extends React.Component {
  constructor(props) {
    super(props);
    this.child = React.createRef();
    this.state = {
      value: "aaa",
    }
  };

  updateChild = () => {
    this.setState({value: "bbb"}, () => {
      this.child.current.changeElements(this.state.value);
    })
  };
  
  render() {
    return (
      <div>
        <button onClick = {this.updateChild} > Click here </button>
        <Child ref={this.child} values={this.state.value} />
      </div>
    );
  }
}

class Child extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: this.props.values,
    };
  }

  changeElements = value => {
    this.setState({ value });
    console.log(value);
  };
  
  render() {
    console.log(this.state.value)
    return (
      <div>{this.state.value}</div>
    );
  }
}

ReactDOM.render( < App / > , document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"></div>