当 useEffect hook 的 body 函数进行条件检查时应该返回什么?

3

我正在使用useEffect钩子,在某些情况下,我不需要返回任何东西。如何处理这种情况最好?

// fooRef is a reference to a textfield (belonging to the same component). Sometimes the fooRef is not there,because of redirections) that's why I need to check if it exists

useEffect(() => fooRef.current && fooRef.current.focus()  , [fooRef])

当按照这种方式使用时,React将会抛出以下错误信息: “effect函数除了用于清理的函数之外,不应该返回任何东西。你返回了null。如果你的effect不需要清理,返回undefined(或什么也不返回)会更好。” 那么最好的选择是返回undefined还是一个空函数呢?
3个回答

6
我认为您想要写的是:
useEffect(() => {if (fooRef.current) fooRef.current.focus()  } , [fooRef])

您目前的实现返回执行 fooRef.current && fooRef.current.focus() 的布尔结果,而不是仅在 fooRef.current 为真时执行 focus 函数。


1
感谢您的输入。看来我缺少的是花括号。正如您所提到的,该函数直接返回布尔结果。 这也可以工作: useEffect(() => { fooRef.current && fooRef.current.focus() } , [fooRef])这是一种肮脏(不好)的模仿if语句的方法,因为只有当foo.current为真(已定义)时,fooRef才会聚焦。 - sotiristherobot

6

0
当您在箭头函数中编写上述语法时,您明确地通知返回fooRef.current.focus(),因此请执行以下操作:
useEffect(() => { if(fooRef.current) fooRef.current.focus() } , [fooRef])

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接