[英]On React, how can I call a function on component mount on a functional/stateless component?
I have this functional/stateless component where I have a function filterByCardinalPoint
which I need to call when component is mounted. 我有这个功能/无状态组件,我有一个函数
filterByCardinalPoint
,我需要在组件安装时调用。 Is there a way to do that without writing the component as a class? 有没有办法在不将组件编写为类的情况下执行此操作?
const PassengersCircle = ({ navigationStore, passengersData }) => {
const filterByCardinalPoint = () => {
const passengersByCardinalPoint = filter('value');
...
};
return (...)
};
You can use the useEffect
hook to run a function when the component has been mounted. 您可以使用
useEffect
挂钩在安装组件时运行函数。 By giving it an empty array as second argument it will only be run after the initial render. 通过给它一个空数组作为第二个参数,它只会在初始渲染后运行。
const PassengersCircle = ({ navigationStore, passengersData }) => {
const filterByCardinalPoint = () => {
const passengersByCardinalPoint = filter('value');
// ...
};
useEffect(() => {
filterByCardinalPoint();
}, []);
return <>{/* ... */}</>;
};
There was no way to emulate lifecycles in functional components before the introduction to hooks in React. 在引入React中的钩子之前,无法模拟功能组件中的生命周期。 You could however use libraries like
recompose
which provided a way to have modular portion of react code as HOCs 但是,您可以使用像
recompose
这样的库,它提供了一种将反应代码的模块化部分作为HOC的方法
However after the introduction of hooks in v16.8.0 you could make use of useEffect
hook to emulate lifecyle like behaviour in functional component. 但是,在v16.8.0中引入钩子之后,您可以使用
useEffect
钩子来模拟功能组件中的生命周期行为。
In order to execute useEffect callback only on initial render you provide an empty array as the second argument. 为了仅在初始渲染时执行useEffect回调,您将提供一个空数组作为第二个参数。 Please refer the docs for more details
有关更多详细信息,请参阅文档
const PassengersCircle = ({ navigationStore, passengersData }) => {
const filterByCardinalPoint = () => {
const passengersByCardinalPoint = filter('value');
...
};
useEffect(() => {
filterByCardinalPoint();
}, [])
return (...)
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.