簡體   English   中英

getDerivedStateFromProps 返回未定義

[英]getDerivedStateFromProps returned undefined

目前是第一次使用 getDerivedStateFromProps。 我的代碼可以正常工作,並且可以執行我希望它執行的操作,但是我在控制台中收到了一條警告,這讓我感到困惑,因為我的代碼正在運行。 警告:“getDerivedStateFromProps():必須返回有效的 state object(或 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;
}

getDerivedStateFromProps方法應返回state 的更新切片,而不是更新作為參數傳遞的 state object。

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

您很可能不需要使用getDerivedStateFromProps官方文檔解釋了原因

似乎您想要做的是根據更改的道具更新 state,在這種情況下componentDidUpdate()更合適,但您似乎正在根據傳入的道具復制 state。

只需在渲染中訪問它們就足夠了; 它們不需要困難的計算。 就像一個虛擬的例子:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM