我不确定当前的行为是否正确。
在 16.3 中,当我有一个通过 props 接收其状态的组件时,我成功地使用了 getDerivedStateFromProps,使用上述函数检查 props 和 state(或者更简洁地说 prevState 和 nextProps)就很好了。它在新道具进入时更新状态,并且状态变化正常运行。
现在在 16.4 中,因为对 setState 的调用也会触发 getDerivedStateFromProps,我看到了意外的结果。它比较的状态已经更新为新状态(逻辑上?)但由于 props 或 nextProps 保持不变,我的比较更新为当前设置的 props。这些在逻辑上没有变化,因为我只改变了状态。所以,我对设置状态的调用现在失败了。也许我做错了?也许它应该与调用 setState 之前的状态进行比较?这是我所期望的,并且可以解决问题,因为真实的先前状态将与道具匹配并且不会发生任何变化。
这是一个例子:https : //jsfiddle.net/rjacks24/1yupwngv/
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
stopped: this.props.stopped || false
};
this.wasToggled = false;
this.toggleStop = this.toggleStop.bind(this);
}
static getDerivedStateFromProps(nextProps, prevState) {
if (prevState.stopped !== nextProps.stopped) {
return { stopped: nextProps.stopped };
}
return null;
}
/**
* function to handle the stop of the antenna
* @returns {void}
*/
toggleStop() {
this.wasToggled = !this.wasToggled;
this.setState({
stopped: !this.state.stopped
});
}
render() {
return (
<div>
<button
type="button"
onClick={this.toggleStop}
className={this.state.stopped ? "done" : ""}
>
Toggle
</button>
State Toggled? {this.state.stopped ? "yes" : "no"}
<div>
But Actually... wasToggled: {this.wasToggled ? "yes" : "no"}{" "}
</div>
</div>
);
}
}
Run Code Online (Sandbox Code Playgroud)
预期的行为是您通过删除 getDerivedStateFromProps() 的代码块而获得的行为,但是,然后不会以应有的方式处理从 heigher 到 props 的更新。
如果我只是做错了,我深表歉意,但由于我在 16.3 中表现出色,如果认为这至少值得讨论。这个人似乎遇到了同样的事情,但我的例子更简单一些:正确使用 React getDerivedStateFromProps
我的猜测是,在这些情况下,正确的方法是始终处理 HOC 上的状态,然后调用 gdsfp 不是问题。
tldr; 16.3 让我在使用 getderivedStateFromProps 时更改状态,16.4 没有。
| 归档时间: |
|
| 查看次数: |
8193 次 |
| 最近记录: |