componentWillMount 用于反应功能组件?

componentWillMount for react functional component?

我想知道对于 React class 组件,我们有 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>
  );
}

  • 正如您提到的,您想要进行 api 调用,它通常发生在 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>
  );
}

实际上,我想在这里添加更多案例,我将制作可重用的自定义钩子。

1.Care 关于额外 dom 渲染

不会造成额外的dom渲染

const useOptimizedComponentWillMount = callback => {
  const mounted = useRef(false)
  if (!mounted.current) callback()

  useEffect(() => {
    mounted.current = true
  }, []);
};

Note: You might want mounted && mounted.current in typescript

2。不关心额外的 dom render

this is exactly

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