我有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)
| 归档时间: |
|
| 查看次数: |
2909 次 |
| 最近记录: |