componentWillMount 用于react功能组件?

IT技术 reactjs react-chartjs react-functional-component
2021-04-21 04:30:42

我想知道对于 React 类组件,我们有componentWillMount()生命周期方法,我们可以在加载组件之前执行任务。诸如调用后端并使用响应来显示该前端中的数据之类的任务。如果我想在功能组件中使用相同的东西怎么办?就像我使用了 react chartJS 一样,为此我想从后端响应中检索数据值,然后图表将根据这些数据填充。

我希望我很好地解释了问题陈述,如果没有,请询​​问任何信息。

2个回答

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>
  );
}

你能帮我解决这个问题吗?stackoverflow.com/questions/62212960/...
2021-06-12 04:30:42
而且它不像 linter 这样的条件不会放手,因为你不能有条件地做钩子?根据我记得的文档,这是一种反模式。
2021-06-17 04:30:42

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

1.关心额外的dom渲染

它不会导致额外的 dom 渲染

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

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

注意:您可能需要mounted && mounted.currenttypescript

2.不要在意额外的dom渲染

这正是托尼的回答

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