将类转换为钩子(if语句中的状态)



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

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
};
}

应该被转换为:setset_time (props. currentanalyzer .reset_time) ?

就像你可以在文档中阅读

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

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

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

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

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

由于这些是状态变量,所以您需要使用useState钩子。

import {useState, useEffect} from 'react'
const ExampleComponent = props => {
const { curentAnalyser } = prop 
const [compState, setCompState] = useState(currentAnalyzer)
}

这会将compState设置为currentAnalyzer对象。你可以在需要的时候改变compState,如:

setCompState(cs => ({
...cs,
[anyField] : anyValue
})

方法2

您可以使用useEffect:

设置状态。
useEffect(() => {
if(currentAnalyzer) setCompState(currentAnalyzer)
}, [currentAnalyzer]

最新更新