[英]React useEffect in function
I've been trying to find a way to use useEffect like this, but I don't think I'm doing it properly:我一直在尝试找到一种像这样使用 useEffect 的方法,但我认为我做得不对:
const [searching, setSearching] = useState(false);
function OnSearch(e) {
const searchValue = e.target.value;
useEffect(() => {
setSearching(true);
}, []);
clearTimeout(timer);
timer = setTimeout(() => {
setSearching(false);
window.location.href = '/block/' + searchValue;
}, 2000);
}
Any kind of help or direction will be appreciated.任何形式的帮助或指导将不胜感激。
I assume from the useState
you've used there that this code is inside a functional component.我从您在那里使用的useState
中假设此代码位于功能组件内。 You don't need or want useEffect
there, just remove it and do setSearching(true)
directly:您不需要或不想在那里useEffect
,只需将其删除并直接执行setSearching(true)
:
const [searching, setSearching] = useState(false);
function OnSearch(e) {
const searchValue = e.target.value;
setSearching(true);
clearTimeout(timer);
timer = setTimeout(() => {
setSearching(false);
window.location.href = '/block/' + searchValue;
}, 2000);
}
(In fact, not only do you not need it, but you can't use hooks anywhere other than the top level of a component function or hook function. So not in an event handler.) (事实上,你不仅不需要它,而且除了组件的顶层 function 或钩子 function 之外,你不能在任何地方使用钩子。所以不能在事件处理程序中使用。)
That leaves the question of the timer
variable.这就留下了timer
变量的问题。 It can't just be a local variable in the component function because that will get recreated on every render.它不能只是组件 function 中的局部变量,因为它将在每次渲染时重新创建。 For non-state instance data like that, you can use an object via useRef
, then use properties on that object, which will be consistent for the lifetime of the component:对于这样的非状态实例数据,您可以通过 useRef 使用useRef
,然后在该 object 上使用属性,这将在组件的生命周期内保持一致:
const [instance] = useRef({});
So that gives us:所以这给了我们:
const [instance] = useRef({});
const [searching, setSearching] = useState(false);
function OnSearch(e) {
const searchValue = e.target.value;
setSearching(true);
clearTimeout(instance.timer);
instance.timer = setTimeout(() => {
setSearching(false);
window.location.href = '/block/' + searchValue;
}, 2000);
}
Side note: In JavaScript, the overwhelmingly-common convention is that only constructor functions and (in React) component functions are capitalized, not other kinds of functions.旁注:在 JavaScript 中,最普遍的约定是只有构造函数和(在 React 中)组件函数被大写,而不是其他类型的函数。 So onSearch
rather than OnSearch
.所以onSearch
而不是OnSearch
。 You can do what you like in your own code of course, but when working with others or asking for help, sticking to conventions helps keep communication clear.你当然可以在自己的代码中做你喜欢的事情,但是在与他人合作或寻求帮助时,遵守约定有助于保持沟通清晰。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.