首页 > 解决方案 > 将类转换为钩子(在 if 语句中声明)

问题描述

我有一个类中的旧代码,我需要将它转换为钩子。我现在已经成功转换了所有内容,除了state在 if 语句中声明的一个代码,我转换的其他代码this.setState在 if 语句中。如何将其转换为钩子?

 if (this.props.curentAnalyser) {
            this.state = {
                ...this.state,
                name: this.props.curentAnalyser.name,
                destination: this.props.curentAnalyser.destination_id,
                cameras: this.props.curentAnalyser.cameras,
                reset_time: this.props.curentAnalyser.reset_time
            };
        }

例如应该将它们转换为: setReset_time(props.curentAnalyser.reset_time) 吗?

标签: javascriptreactjs

解决方案


就像您可以在文档中阅读一样

https://reactjs.org/docs/hooks-intro.html

对于状态,您需要使用 useState() 函数

  const [count, setCount] = useState(0);

对于生命周期,您需要根据您的状态使用 useEffect() 函数

  useEffect(() => {
    // do something
  }, [count]);

推荐阅读