首页 > 解决方案 > getDerivedStateFromProps 返回未定义

问题描述

目前是第一次使用 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;
}

标签: javascriptreactjsgetderivedstatefromprops

解决方案


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


推荐阅读