简体   繁体   English

从 props 设置 React 组件中的状态并在 props 更改时更新?

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

My React component sets a state property called userInGroup based on props.我的 React 组件基于 props 设置了一个名为 userInGroup 的状态属性。

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

This works but does not update when the props change and the value of userInGroup should also change, until I refresh the page.这有效,但在道具更改时不会更新,并且 userInGroup 的值也应该更改,直到我刷新页面。 How can I make this update reactively?如何以被动方式进行此更新?

Maybe I could use componentWillUpdate or componentDidUpdate but then Id be repeating the logic used by userInGroup.也许我可以使用 componentWillUpdate 或 componentDidUpdate 但随后我会重复 userInGroup 使用的逻辑。 Is this repetition inevitable?这种重复是不可避免的吗?

You need to use getDerivedStateFromProps .您需要使用getDerivedStateFromProps The other methods are now deprecated and deemed unsafe.其他方法现在已被弃用并被认为是不安全的。

getDerivedStateFromProps is invoked right before calling the render method, both on the initial mount and on subsequent updates. getDerivedStateFromProps 在调用 render 方法之前调用,无论是在初始安装还是后续更新。 It should return an object to update the state, or null to update nothing.它应该返回一个对象来更新状态,或者返回 null 来不更新任何内容。

This method exists for rare use cases where the state depends on changes in props over time.此方法适用于状态取决于道具随时间变化的罕见用例。 For example, it might be handy for implementing a component that compares its previous and next children to decide which of them to animate in and out.例如,实现一个组件来比较它的前一个和下一个子节点来决定其中的哪个进出动画可能会很方便。

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

Yes you need to make use of componentWillReceiveProps along with constructor/componentDidMount , when you want to update state when props change since constructor/componentDidMount are called only once when the component mounts, and componentWillReceiveProps() is invoked before a mounted component receives new props or the Parent component updates是的,您需要将componentWillReceivePropsconstructor/componentDidMount componentWillReceiveProps一起使用,当您想在 props 更改时更新状态,因为在组件安装时constructor/componentDidMount仅被调用一次,并且componentWillReceiveProps()在安装的组件接收新道具之前被调用或父组件更新

You could write a function that contains the logic您可以编写一个包含逻辑的函数

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