我正在使用 useEffect Hook ,在某些情况下我不需要返回任何东西。处理这种情况的最佳方法是什么?
// 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 会报错并显示以下错误消息: 除用于清理的函数外,效果函数不得返回任何内容。你返回了 null。如果您的效果不需要清理,则返回未定义(或什么都没有)。
最好的选择是返回未定义函数还是空函数?
最佳答案
我想你打算写
useEffect(() => {if (fooRef.current) fooRef.current.focus() } , [fooRef])
您当前的实现是返回执行 fooRef.current && fooRef.current.focus()
的 bool 结果,而不仅仅是执行焦点函数 if fooRef.current
是真的。
关于javascript - 当主体函数进行条件检查时,useEffect 钩子(Hook)应该返回什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58057537/