【问题标题】:getDerivedStateFromProps returned undefinedgetDerivedStateFromProps 返回未定义
【发布时间】: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


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

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

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

    render() {
      const { userName, id } = this.props.currentUser;
      const hasAuthenticated = id && userName;
    
      return (hasAuthenticated)
      ?  <WelcomeMessage />
      :  <Login />
    }
    

    【讨论】:

      猜你喜欢
      • 2019-11-17
      • 1970-01-01
      • 2016-11-18
      • 2019-12-24
      • 2016-05-15
      • 2017-03-11
      • 2019-07-09
      • 2020-10-02
      • 2020-05-22
      相关资源
      最近更新 更多