【发布时间】:2019-09-20 17:41:14
【问题描述】:
目前是第一次使用 getDerivedStateFromProps。我的代码可以正常工作,并且可以执行我希望它执行的操作,但是由于我的代码可以正常工作,因此我在控制台中收到了一条警告,这让我感到困惑。警告:“getDerivedStateFromProps():必须返回有效的状态对象(或 null)。您返回了未定义的。”有没有更好的方法来编写 getDerivedStateFromProps 以消除控制台中的警告?
static getDerivedStateFromProps(props, state) {
state.currentUser.id =
props.location.state && props.location.state.user
? props.location.state.user.id
: state.currentUser.id;
state.currentUser.name =
props.location.state && props.location.state.user
? props.location.state.user.name
: state.currentUser.name;
state.currentUser.roles =
props.location.state && props.location.state.user
? props.location.state.user.roles
: state.currentUser.roles;
state.currentUser.hasAuthenticated = true;
}
【问题讨论】:
-
state.currentUser.id =这会改变状态,这在 React 中是一个很大的禁忌。您应该构造一个新的已修改状态对象并在此函数结束时返回它。 -
getDerivedStateFromProps 在调用 render 方法之前被调用,无论是在初始挂载时还是在后续更新时。它应该返回一个对象来更新状态,或者返回 null 来更新任何内容。
标签: javascript reactjs getderivedstatefromprops