【发布时间】:2018-05-25 15:32:08
【问题描述】:
在这个例子中
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 存储在自己的状态中,并将初始计数传递给子 Counter 组件。
如果从文本框触发的 handleChange 和 initialCount 被更新,子 Counter 组件也会正确更新,因为 getDerivedStateFromProps 静态方法提供了这一点。
但是通过 handleIncrease 和 handleDecrease 方法更新本地状态来更改 Counter 组件中的计数值,这很麻烦。
问题是 getDerivedStateFromProps 这次重新触发并重置计数值。但我没想到这是因为 Counter 组件本地状态更新父 Main 组件没有更新。 UNSAFE_componentWillReceiveProps 就是这样工作的。
总结一下我的 getDerivedStateFromProps 用法不正确,或者我的场景有其他解决方案。
这个版本https://codepen.io/ismail-codar/pen/gzVZqm?editors=1011 好用componentWillReceiveProps
【问题讨论】:
标签: reactjs