React重置非受控组件state的方法

如果想通过props来重置state的值。有3种方法:

1. 最好的方法:key属性

修改key属性的值,可以使组件卸载后重新加载。所有的状态全部重置。

这种情况可以给key设一个每次渲染都会改变的值。

而且在多层嵌套的情况下,避免了组件的diff。

(递归实现树状级联组件,且节点带有状态时,每次都需要重置状态state)

2. 比较特殊属性:getDerivedStateFromProps

在getDerivedStateFromProps周期中,比较props.id的值,来更新state

3. 通过ref调用实例

class App extends React.Component {
   constructor(props) {
      super(props);
      this.ref = React.createRef();
   }
   componnetDidMount() {
      // this.ref.current指向子组件的实例对象this
      this.ref.current.resetData()
   }
   render() {
      // 只能是类子组件
      return <Child ref={this.ref}>
   }
}

class Child extends React.Component {
   resetData = () => {
      // TODO
   }
   render() {
      return <div></div>
   }
}