簡體   English   中英

從 props 設置 React 組件中的狀態並在 props 更改時更新?

[英]Set state in React component from props and update when props change?

我的 React 組件基於 props 設置了一個名為 userInGroup 的狀態屬性。

    this.state = {
        userInGroup: this.props.user
            ? this.props.user.groups.includes(props.group._id)
            : false,
    };

這有效,但在道具更改時不會更新,並且 userInGroup 的值也應該更改,直到我刷新頁面。 如何以被動方式進行此更新?

也許我可以使用 componentWillUpdate 或 componentDidUpdate 但隨后我會重復 userInGroup 使用的邏輯。 這種重復是不可避免的嗎?

您需要使用getDerivedStateFromProps 其他方法現在已被棄用並被認為是不安全的。

getDerivedStateFromProps 在調用 render 方法之前調用,無論是在初始安裝還是后續更新。 它應該返回一個對象來更新狀態,或者返回 null 來不更新任何內容。

此方法適用於狀態取決於道具隨時間變化的罕見用例。 例如,實現一個組件來比較它的前一個和下一個子節點來決定其中的哪個進出動畫可能會很方便。

static getDerivedStateFromProps(props) {
  return {
    userInGroup: props.user
      ? props.user.groups.includes(props.group._id)
      : false,
  }
}

是的,您需要將componentWillReceivePropsconstructor/componentDidMount componentWillReceiveProps一起使用,當您想在 props 更改時更新狀態,因為在組件安裝時constructor/componentDidMount僅被調用一次,並且componentWillReceiveProps()在安裝的組件接收新道具之前被調用或父組件更新

您可以編寫一個包含邏輯的函數

this.state = {
        userInGroup: this.getUserStatus();
    };

componentWillReceiveProps(nextProps) {
    if(nextProps.user !== this.props.user) {
        this.setState({userInGroup: this.getUserStatus(nextProps)})
    }
}
getUserStatus = (newProps) => {
    const data = newProps || this.props
    return data.user
            ? data.user.groups.includes(data.group._id)
            : false
}

暫無
暫無

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

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