使用效果调用API几次Reactjs
我在React组件中具有此使用效应函数。我在此处调用API VideGridState
。 现在,这里发生的事情是在“伦理”页面上召集我的API 2倍,而计数发生变化时第二个。我希望当页面重新加载时将其称为单个时间。但是,当streamSearchText
更改时,
const [count, setCount] = useState(0);
const [streamSearchText, setStreamSearchText] = useState("");
useEffect(() => {
videoGridState();
}, [count]);
useEffect(() => {
const delayDebounceFn = setTimeout(() => {
setCount(count + 1);
}, 1000);
return () => clearTimeout(delayDebounceFn);
}, [streamSearchText]);
我该怎么做?
I have this useEffect function in react component. I am calling api videoGridState
here.
Now what is happening here it is calling my api 2 times one at intitial page reaload and second one when count is changing. I want it to be called single time when page reloads. But also when streamSearchText
changes
const [count, setCount] = useState(0);
const [streamSearchText, setStreamSearchText] = useState("");
useEffect(() => {
videoGridState();
}, [count]);
useEffect(() => {
const delayDebounceFn = setTimeout(() => {
setCount(count + 1);
}, 1000);
return () => clearTimeout(delayDebounceFn);
}, [streamSearchText]);
How can I do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
主要问题是您拥有两个
使用效果
调用,因此它们每个都处理了,第二个触发了第一个(延迟之后),从而导致重复。据我了解,您的目标是:
videigridState
立即在安装座上,并在每当
streamSearchText
更改转弯 令人惊讶的是尴尬。我可能最终会使用Ref:实时示例:
当
streamSearchText
是>时,您也可以立即进行查询代码>“” ,而不仅仅是在安装上。这可能足够好,具体取决于您需要的严格程度。另外,但是,如果您仍在看到两次“坐骑”上发生的事情,则可能会在应用程序周围使用
react.strictmode
运行库的开发副本(许多脚手架系统中的默认值)。请参阅此问题的答案.strictMode 可能会多次安装组件,并引起其他似乎令人惊讶的。The main issue is that you have two
useEffect
calls, and so they're each handled, and the second triggers the first (after a delay), resulting in the duplication.As I understand it, your goal is:
videoGridState
immediately on mount, andstreamSearchText
changesThat turns out to be surprisingly awkward to do. I'd probably end up using a ref for it:
Live Example:
You could also do the query immediately when
streamSearchText
is""
, but that would happen every timestreamSearchText
was""
, not just on mount. That may be good enough, depending on how rigorous you need to be.Additionally, though, if you're still seeing something happen "on mount" twice, you may be running a development copy of the libraries with
React.StrictMode
around your app (the default in many scaffolding systems). See this question's answers for details on howReact.StrictMode
may mount your component more than once and throw in other seeming surprises.您的以下
useseffect()
函数使此行为实现:因为它最初运行但称为
setCount()
,它更新了状态,并迫使组件重新渲染哪个依次运行第一个useeffect()
,因为在依赖项数组中具有[count]
。因此,
[count]
的周期继续Your following
useEffect()
function makes this behaviour to happen:Since it runs initially but called
setCount()
which updates the state, and forces a re-render of the component which in turn runs the firstuseEffect()
since that has[count]
in the dependency array.And hence the cycle continues for the
[count]