在React的功能组件中,有方法通过钩子来模拟componentDidMount吗?
当前回答
关于钩子内异步函数的信息:
效果回调是同步的,以防止竞争条件。把async函数放在里面:
useEffect(() => {
async function fetchData() {
// You can await here
const response = await MyAPI.getData(someId);
// ...
}
fetchData();
}, [someId]); // Or [] if effect doesn't need props or state
其他回答
对于钩子的稳定版本(React version 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);
当count增加时,你想重新渲染你的函数组件。然后你的useEffect应该看起来像这样
useEffect(() => {
// <div>{count}</div>
}, [count]);
这样,每当你的计数更新你的组件将重新呈现。希望这对你有所帮助。
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>
您希望使用useEffect(),这取决于您如何使用函数,可以像componentDidMount()一样工作。
如。你可以使用一个自定义的加载状态属性,初始设置为false,并在呈现时将其切换为true,并且仅在该值发生变化时触发效果。
文档
关于钩子内异步函数的信息:
效果回调是同步的,以防止竞争条件。把async函数放在里面:
useEffect(() => {
async function fetchData() {
// You can await here
const response = await MyAPI.getData(someId);
// ...
}
fetchData();
}, [someId]); // Or [] if effect doesn't need props or state