gpt4 book ai didi

reactjs - 用 useEffect 替换 componentDidUpdate

转载 作者:行者123 更新时间:2023-12-05 01:35:46 24 4
gpt4 key购买 nike

我正在将基于类的组件中的生命周期方法替换为 useEffect Hook ,因为我喜欢功能组件。我不确定我是否正确使用了 useEffect..

我们不能在 useEffect 中指向之前的状态或 Prop ,我该如何用 useEffect 处理这些?

假设我们有一个名为 src 的 Prop ,我想检查这个 src 是否已经改变,如果没有,会有一些逻辑。

componentDidUpdate(prevProps) {
const { src } = this.props;

if(prevProps.src !== src) {
this.cleanUp();
this.init();
} else{
// todo something
}
}

如何使用 useEffect 处理这个问题?

最佳答案

想想 useEffect 在这种情况下有一个“钩子(Hook)”,它依赖于某些东西在发生变化时触发它。

如果您不给 useEffect 任何东西,它只会在加载时触发一次。这相当于 componentDidMount

如果你给它多个对象或元素,它会根据这些元素的变化触发。

长话短说:

const App = props => {
useEffect(() => {
// your code
}, [props.yourPropertyToWatch]);
}

更新

基于 @hmr的反馈,最好也添加清理,这相当于 componentWillUnmount

const App = props => {
useEffect(() => {
// your code

// once done with the component
return () => {
// your unmount code
}
}, [props.yourPropertyToWatch]);
}

关于reactjs - 用 useEffect 替换 componentDidUpdate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62654874/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com