首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >getDerivedStateFromProps返回未定义

getDerivedStateFromProps返回未定义
EN

Stack Overflow用户
提问于 2019-09-20 17:41:14
回答 2查看 3.2K关注 0票数 2

目前首次使用getDerivedStateFromProps。我的代码可以工作,它可以做我想做的事情,但是我在我的控制台中收到了一个警告,这让我感到困惑,因为我的代码正在工作。警告:"getDerivedStateFromProps():必须返回有效的状态对象(或null)。您已返回未定义的状态对象。“是否有更好的方法来编写getDerivedStateFromProps以消除控制台中的警告?

代码语言:javascript
复制
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;
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-09-20 17:52:17

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

代码语言:javascript
复制
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的其他字段被保存到新的状态中。

票数 2
EN

Stack Overflow用户

发布于 2019-09-20 21:21:13

您很可能不需要使用getDerivedStateFromProps官方文件解释为什么

您想要做的似乎是根据更改道具更新状态,在这种情况下,componentDidUpdate()更合适,但您似乎是在根据传入的道具复制状态。

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

代码语言:javascript
复制
render() {
  const { userName, id } = this.props.currentUser;
  const hasAuthenticated = id && userName;

  return (hasAuthenticated)
  ?  <WelcomeMessage />
  :  <Login />
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58032963

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档