sot*_*bot 1 javascript reactjs react-hooks
我正在使用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])
Run Code Online (Sandbox Code Playgroud)
当以这种方式使用它时,React会抱怨以下错误消息: 效果函数除用于清理的函数外,不得返回任何其他内容。您返回了null。如果您的效果不需要清理,则返回undefined(或不返回)。
最好的选择是返回未定义或空函数吗?
我想你打算写
useEffect(() => {if (fooRef.current) fooRef.current.focus() } , [fooRef])
Run Code Online (Sandbox Code Playgroud)
您当前的实现返回的是执行的布尔结果,fooRef.current && fooRef.current.focus()
而不是如果fooRef.current
为true 则仅执行focus函数。
您可以使用void
:
useEffect(() => void rooRef.current && fooRef.current.focus(), [fooRef])
Run Code Online (Sandbox Code Playgroud)
看到它肯特C.兹视频:使用void
使箭头函数返回什么
归档时间: |
|
查看次数: |
96 次 |
最近记录: |