所以 16.4 “修复”了 getDerivedStateFromProps 中的一个错误,现在它在道具更改和状态更改时都会被触发。显然这是有意的,来自这篇文章:https ://github.com/facebook/react/issues/12898 。但是对我来说,在该州保存以前的道具是一个很大的矫枉过正,所以我想问是否有人已经制定了处理这样的案例的程序:
class Componentche extends React.Component {
state = {
valuesForInput: {
input1: ''
}
}
static getDerivedStateFromProps(props, state) {
if (props.someInitialValuesForInput.input1 !== state.valuesForInput.input1) {
return {
valuesForInput: {
...state,
input1: props.someInitialValuesForInput.input1
}
}
}
return state;
render () {
<Input value='valuesForInput.input1' onChange='(e) => setState({valuesForInput: {...this.state, input1: e.target.value }})'
}
}
所以在上述情况下,我永远不会改变输入,因为 getDerivedStateFromProps 将在收到的新道具和 setState 触发器上执行,我的条件甚至永远不会为假。
那么处理这种情况的正确方法是什么?我是否真的需要将旧道具保留在状态中并将它们也用于条件?
我刚从React看到这篇文章,但他们没有提供可行的替代方案。
谢谢你的帮助!