我想知道对于 React 类组件,我们有componentWillMount()生命周期方法,我们可以在加载组件之前执行任务。诸如调用后端并使用响应来显示该前端中的数据之类的任务。如果我想在功能组件中使用相同的东西怎么办?就像我使用了 react chartJS 一样,为此我想从后端响应中检索数据值,然后图表将根据这些数据填充。
我希望我很好地解释了问题陈述,如果没有,请询问任何信息。
我想知道对于 React 类组件,我们有componentWillMount()生命周期方法,我们可以在加载组件之前执行任务。诸如调用后端并使用响应来显示该前端中的数据之类的任务。如果我想在功能组件中使用相同的东西怎么办?就像我使用了 react chartJS 一样,为此我想从后端响应中检索数据值,然后图表将根据这些数据填充。
我希望我很好地解释了问题陈述,如果没有,请询问任何信息。
componentWillMount
仅在初始渲染前调用一次。我制作了一个示例代码,请在下面查看
import React, { useState, useEffect } from "react";
import "./styles.css";
export default function App() {
const [mounted, setMounted] = useState(false)
if(!mounted){
// Code for componentWillMount here
// This code is called only one time before intial render
}
useEffect(() =>{
setMounted(true)
},[])
return (
<div className="App">
</div>
);
}
componentDidmount
,您可以简单地使用useEffect
带有空数组的钩子作为功能组件中的依赖项import React, { useState, useEffect } from "react";
import "./styles.css";
export default function App() {
const [mounted, setMounted] = useState(false)
useEffect(() =>{
// This is similar to componentDidMount
// Call back-end api here
},[])
return (
<div className="App">
</div>
);
}
其实我想在这里添加更多的案例,我将制作可重用的自定义钩子。
它不会导致额外的 dom 渲染
const useOptimizedComponentWillMount = callback => {
const mounted = useRef(false)
if (!mounted.current) callback()
useEffect(() => {
mounted.current = true
}, []);
};
注意:您可能需要
mounted && mounted.current
typescript
这正是托尼的回答
const useComponentWillMount = callback => {
const [mounted, setMounted] = useState(false)
if (!mounted) callback()
useEffect(() => {
setMounted(true)
}, [])
};
const App = () => {
useComponentWillMount(() => console.log("will mount"))
return console.log("render-dom") || <div>Layout</div>
};
// will mount
// (2)render-dom
const App = () => {
useOptimizedComponentWillMount(() => console.log("will mount"))
return console.log("render-dom") || <div>Layout</div>
};
// will mount
// render-dom