我的React组件基于道具设置一个名为userInGroup的状态属性。
this.state = {
userInGroup: this.props.user
? this.props.user.groups.includes(props.group._id)
: false,
};
这可以工作,但不更新时,道具的变化和userInGroup的值也应该改变,直到我刷新页面。我如何才能使此更新反应?
也许我可以使用组件WillUpdate或组件DDUpdate,但我会重复用户InGroup使用的逻辑。这种重复是不可避免的吗?
您需要使用getDerivedStateFromProps。其他方法现在已被弃用,并被视为不安全。
在调用呈现方法之前调用getDerivedStateFromProps,无论是在初始挂载还是后续更新中。它应该返回一个对象来更新状态,或者返回null来不更新任何内容。
这种方法适用于状态取决于道具随时间变化的罕见用例。例如,实现一个组件可能很方便,该组件比较其上一个和下一个子级,以决定对其中哪个进行动画处理。
static getDerivedStateFromProps(props) {
return {
userInGroup: props.user
? props.user.groups.includes(props.group._id)
: false,
}
}
是的,您需要使用componentWillReceiveProps
以及constructor/componentDidMount
,因为组件装载时只调用一次constructor/componentDidMount
,当您想要更新道具更改时的状态,并且在装入的组件接收新的道具或父组件更新之前调用componentWillReceiveProps()
你可以写一个包含逻辑的函数
this.state = {
userInGroup: this.getUserStatus();
};
componentWillReceiveProps(nextProps) {
if(nextProps.user !== this.props.user) {
this.setState({userInGroup: this.getUserStatus(nextProps)})
}
}
getUserStatus = (newProps) => {
const data = newProps || this.props
return data.user
? data.user.groups.includes(data.group._id)
: false
}