在React的功能组件中,有方法通过钩子来模拟componentDidMount吗?


当前回答

componentDidMount()的等效钩子是

useEffect(()=>{},[]);

希望这对你有帮助。

其他回答

componentDidMount()的等效钩子是

useEffect(()=>{},[]);

希望这对你有帮助。

import React, { useState, useEffect } from 'react';

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

  // Similar to componentDidMount and componentDidUpdate:
  useEffect(() => {
    // Update the document title using the browser API
    document.title = `You clicked ${count} times`;
  });

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

请访问这个官方文件。很容易理解最新的方式。

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

您希望使用useEffect(),这取决于您如何使用函数,可以像componentDidMount()一样工作。

如。你可以使用一个自定义的加载状态属性,初始设置为false,并在呈现时将其切换为true,并且仅在该值发生变化时触发效果。

文档

useLayoutEffect钩子是React钩子中ComponentDidMount的最佳替代方案。 useLayoutEffect钩子在渲染UI之前执行,useEffect钩子在渲染UI之后执行。根据您的需要使用它。 示例代码:

import { useLayoutEffect, useEffect } from "react";

export default function App() {
  useEffect(() => {
    console.log("useEffect Statements");
  }, []);

  useLayoutEffect(() => {
    console.log("useLayoutEffect Statements");
  }, []);
  return (
    <div>
      <h1>Hello Guys</h1>
    </div>
  );
}
 

在功能组件上没有componentDidMount,但是React Hooks提供了一种方法,可以通过使用useEffect钩子来模拟行为。

将一个空数组作为第二个参数传递给useEffect(),以仅在挂载时运行回调。

请阅读有关useEffect的文档。

function ComponentDidMount() { const [count, setCount] = React.useState(0); React.useEffect(() => { console.log('componentDidMount'); }, []); return ( <div> <p>componentDidMount: {count} times</p> <button onClick={() => { setCount(count + 1); }} > Click Me </button> </div> ); } ReactDOM.render( <div> <ComponentDidMount /> </div>, document.querySelector("#app") ); <script src="https://unpkg.com/react@16.7.0-alpha.0/umd/react.development.js"></script> <script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script> <div id="app"></div>