在React的功能组件中,有方法通过钩子来模拟componentDidMount吗?
当前回答
useEffect()钩子允许我们实现componentDidMount功能,componentDidUpdate componentWillUnMount功能。
useEffect()的不同语法允许实现上述每一种方法。
我)componentDidMount
useEffect(() => {
//code here
}, []);
(二)componentDidUpdate
useEffect(() => {
//code here
}, [x,y,z]);
//where x,y,z are state variables on whose update, this method should get triggered
3) componentDidUnmount
useEffect(() => {
//code here
return function() {
//code to be run during unmount phase
}
}, []);
你可以查看官方react网站获取更多信息。hook的官方反应页面
其他回答
在功能组件上没有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>
关于钩子内异步函数的信息:
效果回调是同步的,以防止竞争条件。把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
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>
);
}
您希望使用useEffect(),这取决于您如何使用函数,可以像componentDidMount()一样工作。
如。你可以使用一个自定义的加载状态属性,初始设置为false,并在呈现时将其切换为true,并且仅在该值发生变化时触发效果。
文档
useEffect()钩子允许我们实现componentDidMount功能,componentDidUpdate componentWillUnMount功能。
useEffect()的不同语法允许实现上述每一种方法。
我)componentDidMount
useEffect(() => {
//code here
}, []);
(二)componentDidUpdate
useEffect(() => {
//code here
}, [x,y,z]);
//where x,y,z are state variables on whose update, this method should get triggered
3) componentDidUnmount
useEffect(() => {
//code here
return function() {
//code to be run during unmount phase
}
}, []);
你可以查看官方react网站获取更多信息。hook的官方反应页面