版权声明:转载请注明出处 https://blog.csdn.net/qdmoment/article/details/85328694
在设计组件时,最重要的是决定它的数据是否需要被控制。
与其尝试在状态中镜像一个属性值,不如让组件被控制,并在某些父组件的状态中合并两个不同的值。
例如,与其让子组件既接收一个“committed”属性又要维护一个“draft”的状态,不如让父级组件同时管理两个状态——state.committedValue
和state.draftValue
——直接控制子组件的值。这使得数据流更加清晰和可预测。
对于非受控的组件,如果您试图在某特定的属性(通常是ID)更改时重置状态,那么您有几个选项:
推荐:如果要重置全部内部状态,使用key
特性
备选 1:只重置某些特定的状态字段,关注特定属性的更改(例如props.userID
)。
class EmailInput extends Component {
state = {
email: this.props.defaultEmail,
prevPropsUserID: this.props.userID
};
static getDerivedStateFromProps(props, state) {
// Any time the current user changes,
// Reset any parts of state that are tied to that user.
// In this simple example, that's just the email.
if (props.userID !== state.prevPropsUserID) {
return {
prevPropsUserID: props.userID,
email: props.defaultEmail
};
}
return null;
}
// ...
}
备选 2:您还可以考虑使用refs调用一个命令式实例方法。
class EmailInput extends Component {
state = {
email: this.props.defaultEmail
};
resetEmailForNewUser(newEmail) {
this.setState({ email: newEmail });
}
// ...
}