getDerivedStateFromProps 返回未定义

getDerivedStateFromProps returned undefined

目前第一次使用getDerivedStateFromProps。我的代码可以正常工作,并且可以执行我希望它执行的操作,但是我在控制台中收到一条警告,这让我很困惑,因为我的代码正在运行。警告:"getDerivedStateFromProps(): A valid state object (or null) must be returned. You have returned undefined." 是否有更好的方法来编写 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;
}

getDerivedStateFromProps 方法应该 return 状态的更新切片,而不是更新作为参数传递的状态对象。

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 的其他一些字段保留到新状态。

您很可能不需要使用 getDerivedStateFromPropsofficial docs explaining why

看来你想做的是根据改变的道具更新状态,在这种情况下 componentDidUpdate() 更合适,而且,你似乎是根据传入的道具复制状态。

只需在渲染中访问它们就足够了;他们不需要困难的计算。就像一个虚拟的例子:

render() {
  const { userName, id } = this.props.currentUser;
  const hasAuthenticated = id && userName;

  return (hasAuthenticated)
  ?  <WelcomeMessage />
  :  <Login />
}