有没有办法通过钩子在React功能组件中模拟componentDidMount
对于稳定版本的挂钩(React版本16.8.0+)
对于componentDidMount
useffect(()=>{
//你的代码在这里
}, []);
对于componentdiddupdate
useffect(()=>{
//你的代码在这里
},[yourDependency]);
对于组件,将卸载
useffect(()=>{
//组件将卸载
返回()=>{
//你的代码在这里
}
},[yourDependency]);
因此,在这种情况下,需要将依赖项传递到此数组中。假设你有一个这样的状态
const[count,setCount]=useState(0)
当计数增加时,您希望重新呈现函数组件。那么您的useffect应该如下所示
useffect(()=>{
//<;div>;{count}<;/div>;
},[计数];
这样,每当计数更新时,组件都将重新渲染。希望这会有所帮助