componentDidMount 等效于 React 函数/Hooks 组件吗? [英] componentDidMount equivalent on a React function/Hooks component?

查看:50
本文介绍了componentDidMount 等效于 React 函数/Hooks 组件吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法通过钩子在 React 功能组件中模拟 componentDidMount?

Are there ways to simulate componentDidMount in React functional components via hooks?

推荐答案

针对稳定版 hooks (React Version 16.8.0+)

For the stable version of hooks (React Version 16.8.0+)

对于componentDidMount

useEffect(() => {
  // Your code here
}, []);

对于 componentDidUpdate

useEffect(() => {
  // Your code here
}, [yourDependency]);

对于 componentWillUnmount

useEffect(() => {
  // componentWillUnmount
  return () => {
     // Your code here
  }
}, [yourDependency]);

所以在这种情况下,您需要将您的依赖项传递到这个数组中.假设你有这样的状态

So in this situation, you need to pass your dependency into this array. Let's assume you have a state like this

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

每当计数增加时,您都想重新渲染您的功能组件.那么你的 useEffect 应该是这样的

And whenever count increases you want to re-render your function component. Then your useEffect should look like this

useEffect(() => {
  // <div>{count}</div>
}, [count]);

这样,每当您的计数更新时,您的组件都会重新渲染.希望这会有所帮助.

This way whenever your count updates your component will re-render. Hopefully this will help a bit.

这篇关于componentDidMount 等效于 React 函数/Hooks 组件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆