[英]How trigger UseEffect Once with dependencies?
I have a useEffect()
Method, that runs once when the component is loaded.我有一个
useEffect()
方法,它在组件加载时运行一次。
useEffect(() => {
(async function fetchData() {
const results = await stateIsoAPI();
setStates(results); // API results to other trigger other Use effect
})();
}, []);
But I need only when the user type info for first time.但我只有在用户第一次输入信息时才需要。
If I add state dependency of input value it triggers every time that user type:如果我添加输入值的 state 依赖项,它会在每次用户键入时触发:
useEffect(() => {
(async function fetchData() {
const results = await stateIsoAPI();
setStates(results); // API results to other trigger other Use effect
})();
}, [<inputValueState>]);
But it is not the desired behavior.但这不是期望的行为。 How can solve it?
怎么解决?
Add a fast-exit condition before IIFE
在
IIFE
之前添加快速退出条件
useEffect(() => {
if(!isFirstTime(<inputValueState>)) {
return () => {}
}
(async function fetchData() {
const results = await stateIsoAPI();
setStates(results); // API results to other trigger other Use effect
})();
}, [<inputValueState>]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.