在路由进入之前或componentMount之前如何在react hook中获取数据?

我在我的React项目中使用功能组件和挂钩。对于类组件,存在componentWillMount处理程序。但是我找不到功能组件的替代品。 Vue具有beforeRouteEnter()处理函数,它非常酷。当用户单击链接时,浏览器1.获取数据2.呈现页面。我找到了一些有关“数据加载”实现的示例,但我认为这不是很好的方法。

如何实现功能组件和钩子的反应项目在路由进入之前实现数据获取?谢谢!

评论
xet
xet

componentWillMount is deprecated because of the miss use of it. Most peoples try to use it to fetch data but the problem is data is not return until the component is rendered so what happen now is re render the component again.

The best place to fetch data is componentDidMount or in Angular ngOnInit ( Don't know about Vue )

So in hooks you can use useEffect() with empty array as 2nd argument to implement the behavior of componentDidMount.

useEffect(() => {/*fetch data*/}, [])
点赞
评论
sit_in
sit_in

componentWillMount and onEnter methods have been deprecated by react and react-router.

In order to fetch data within our rendered Route you are advised to use componentDidMount for class components and useEffect for functional components

例如:

const Comp = () => {
   const [loading, setIsLoading] = useState(true);
   useEffect(() => {
      // Fetch data and set in state and set loading to false
   }, []) // Dependency can be empty of have route params dependending on requirement

}
点赞
评论