如何在React中编写和读取组件状态?

iro*_*rom 8 reactjs

我有MyComponent使用setData()在state中写入数据,getData()用于读取状态.这是React的最佳实践吗?它对我来说很好,但不确定我做的是最简单的方法,请建议

class MyComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: []
    };

  }

  setData(){    
    this.setState({data:"123"});   
  }

  getData() {
    console.log(this.state.data); // 123 OK !!!   
  }

  componentDidMount() {    
    this.setData();  

  }
  componentDidUpdate() { 
    this.getData();
  }
  render() {
    return (                     
       <div>           
          {this.state.data} // 123 OK !!!
       </div>                        
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

JiN*_*JiN 5

完全没有理由这样做。this.state.data只需在需要使用的地方使用即可。

如果您想在子组件中使用状态数据,请将其作为 prop 传递,您还可以将一个函数传递给子组件来更改父组件的状态。

来源