如何使用 componentWillReceiveProps 模仿 useEffect?

时间:2021-07-12 01:42:42

标签: javascript reactjs

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

clearAllCache()

在类组件中是这样的。我尝试的是

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 作为参数。所以,我不确定我应该如何设置一个状态来检测状态的变化。

有什么帮助吗?

1 个答案:

答案 0 :(得分:3)

您可能想使用 componentDidUpdate,而不是 componentWillReceiveProps。 componentWillReceiveProps is going to be removed from 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 中执行类似的代码。