在这个例子中。
期望结果: 点击“+”、“-”按钮和文本框更改必须更新计数器。
当前情况: 主组件将initialCount存储在自己的状态中,并将初始计数传递给子计数器组件。
如果从文本框触发handleChange并更新了initialCount,那么子计数器组件也会正确更新,因为getDerivedStateFromProps静态方法提供了这个功能。
但是,通过使用handleIncrease和handleDecrease方法更新局部状态来更改计数器组件中的计数值是有问题的。
问题是getDerivedStateFromProps重新触发,然后重置计数值。但我没有预料到这一点,因为计数器组件中的局部状态更新父Main组件并不会更新。UNSAFE_componentWillReceiveProps就是这样工作的。
总之,我的getDerivedStateFromProps用法不正确,或者我的场景有另外一种解决方案。
此版本 https://codepen.io/ismail-codar/pen/gzVZqm?editors=1011 与componentWillReceiveProps很好地配合使用。
https://codepen.io/ismail-codar/pen/QrXJgE?editors=1011
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
static getDerivedStateFromProps(nextProps, prevState) {
console.log("nextProps", nextProps, "\nprevState", prevState)
if(nextProps.count !== prevState.count)
return {count: nextProps.count};
else
return null;
}
handleIncrease(e) {
this.setState({count: this.state.count + 1})
}
handleDecrease(e) {
this.setState({count: this.state.count - 1})
}
render() {
return <div>
<button onClick={this.handleIncrease.bind(this)}>+</button>
{this.state.count}
<button onClick={this.handleDecrease.bind(this)}>-</button>
</div>;
}
}
class Main extends React.Component {
constructor(props) {
super(props);
this.state = { initialCount: 1 };
}
handleChange(e) {
this.setState({initialCount: e.target.value})
}
render() {
return <div>
<Counter count={this.state.initialCount} />
<hr/>
Change initial:<input type="number" onChange={this.handleChange.bind(this)} value={this.state.initialCount} />
</div>
}
}
ReactDOM.render(
<Main/>,
document.getElementById("root")
);
期望结果: 点击“+”、“-”按钮和文本框更改必须更新计数器。
当前情况: 主组件将initialCount存储在自己的状态中,并将初始计数传递给子计数器组件。
如果从文本框触发handleChange并更新了initialCount,那么子计数器组件也会正确更新,因为getDerivedStateFromProps静态方法提供了这个功能。
但是,通过使用handleIncrease和handleDecrease方法更新局部状态来更改计数器组件中的计数值是有问题的。
问题是getDerivedStateFromProps重新触发,然后重置计数值。但我没有预料到这一点,因为计数器组件中的局部状态更新父Main组件并不会更新。UNSAFE_componentWillReceiveProps就是这样工作的。
总之,我的getDerivedStateFromProps用法不正确,或者我的场景有另外一种解决方案。
此版本 https://codepen.io/ismail-codar/pen/gzVZqm?editors=1011 与componentWillReceiveProps很好地配合使用。