我在我的React项目中使用功能组件和挂钩。对于类组件,存在componentWillMount处理程序。但是我找不到功能组件的替代品。 Vue具有beforeRouteEnter()处理函数,它非常酷。当用户单击链接时,浏览器1.获取数据2.呈现页面。我找到了一些有关“数据加载”实现的示例,但我认为这不是很好的方法。
如何实现功能组件和钩子的反应项目在路由进入之前实现数据获取?谢谢!
我在我的React项目中使用功能组件和挂钩。对于类组件,存在componentWillMount处理程序。但是我找不到功能组件的替代品。 Vue具有beforeRouteEnter()处理函数,它非常酷。当用户单击链接时,浏览器1.获取数据2.呈现页面。我找到了一些有关“数据加载”实现的示例,但我认为这不是很好的方法。
如何实现功能组件和钩子的反应项目在路由进入之前实现数据获取?谢谢!
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 AngularngOnInit
( Don't know about Vue )So in hooks you can use useEffect() with empty array as 2nd argument to implement the behavior of
componentDidMount
.componentWillMount
andonEnter
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 anduseEffect
for functional components例如: