繁体   English   中英

如何使用 componentWillReceiveProps 模仿 useEffect?

[英]How do I imitate useEffect using componentWillReceiveProps?

我对函数式组件比较熟悉,但是我必须修复一些之前构建的类组件。 我想做的是,

useEffect(() => {
    if (state1) {
        // do this
        // change state state1 -> false
    }
}, [state1])

在类组件中类似这样的东西。 我试过的是

componentWillReceiveProps = (nextProps) => {
    if (nextProps.state1 !== this.props.state1) {
      if (nextProps.state1) {
          // do this
      } else {
        // revert this
      }
      // update state
      this.setState({ state1: !this.state.state1 });
    }
  }

显然,这很奇怪。 但是我很困惑,因为componentWillReceiveProps接收一个prop作为参数。 所以,我不确定我应该如何设置一个状态来检测状态的变化。

有什么帮助吗?

您可能想要使用 componentDidUpdate,而不是 componentWillReceiveProps。 componentWillReceiveProps 将从 react 中移除,并且它经常被滥用。

使用 componentDidUpdate,您将执行以下操作:

componentDidUpdate(prevProps, prevState) {
  if (this.state.state1 !== prevState.state1) {
    if (this.state.state1) {
      // do this
      // change state state1 -> false
      this.setState({ state1: false });
    }
  }
}

如果您也需要在第一次渲染后运行此代码,您可能需要在 componentDidMount 中执行类似的代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM