是否可以通过钩子(Hook)在React功能组件中模拟componentDidMount

最佳答案

对于钩子(Hook)的稳定版本( react 版本16.8.0+)

对于componentDidMount

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

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

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

因此,在这种情况下,您需要将依赖项传递给此数组。假设您处于这样的状态
const [count, setCount] = useState(0);
每当计数增加时,您都希望重新呈现功能组件。然后你的useEffect应该看起来像这样
useEffect(() => {
  // <div>{count}</div>
}, [count]);

这样,无论何时更新计数,组件都将重新呈现。希望这会有所帮助。

关于javascript - componentDidMount是否等效于React函数/Hooks组件?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53945763/

10-12 12:19
查看更多