目前首次使用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;
}发布于 2019-09-20 17:52:17
getDerivedStateFromProps方法应该返回更新后的状态片,而不是更新作为参数传递的状态对象。
return {
currentUser: {
...state.currentUser,
id: props.location.state && props.location.state.user ? props.location.state.user.id : state.currentUser.id,
name: props.location.state && props.location.state.user ? props.location.state.user.name : state.currentUser.name,
roles: props.location.state && props.location.state.user ? props.location.state.user.roles : state.currentUser.roles,
hasAuthenticated: true;
}
}我添加了...state.currentUser,以防state.currentUser的其他字段被保存到新的状态中。
发布于 2019-09-20 21:21:13
您很可能不需要使用getDerivedStateFromProps:官方文件解释为什么。
您想要做的似乎是根据更改道具更新状态,在这种情况下,componentDidUpdate()更合适,但您似乎是在根据传入的道具复制状态。
在渲染中简单地访问它们就足够了;它们不需要困难的计算。就像一个虚拟的例子:
render() {
const { userName, id } = this.props.currentUser;
const hasAuthenticated = id && userName;
return (hasAuthenticated)
? <WelcomeMessage />
: <Login />
}https://stackoverflow.com/questions/58032963
复制相似问题