React 钩子需要返回一个值吗?

Hyp*_*per 14 javascript reactjs redux react-hooks

我最近开始在我的 React 应用程序中构建自定义钩子,并一直在关注 React 网站上的文档。但是,我正在构建的钩子不需要返回值,因为它们在初始化时为 Redux 设置数据。

例子:

// custom hook
export const useSetup() {
  useEffect(() => {
    if (data) fetch().then(data => dispatch(setInit(data)))
  }, [dispatch])
}


// functional component
export function Details() {
  useSetup()
Run Code Online (Sandbox Code Playgroud)

我找不到明确说明钩子需要返回任何内容的文档。但是,我找不到钩子不返回内容的示例。有人可以建议这种方法是否正确吗?

Yve*_*can 27

是的,你的做法是正确的。React hooks 不需要返回任何东西。React文档指出:

\n
\n

我们不需要从效果中返回一个命名函数。我们在这里将其称为\ncleanup 是为了阐明其目的,但您可以返回一个箭头\n函数或将其称为不同的名称。

\n
\n

作为参数传递给钩子的函数的返回值在其所属的 React 组件的生命周期中具有特殊用途。本质上,该返回值应该是一个函数,并在带有钩子的组件重新渲染或卸载之前执行。React 文档将这种钩子称为“清理效果”。

\n

React 文档使用下面的示例来展示钩子的useEffect样子:

\n
const [count, setCount] = useState(0);\n\n// Similar to componentDidMount and componentDidUpdate:\nuseEffect(() => {\n  // Update the document title using the browser API\n  document.title = `You clicked ${count} times`;\n});\n
Run Code Online (Sandbox Code Playgroud)\n

正如您所看到的,用作参数的匿名函数useEffect没有return语句。

\n

您可以通过稍微更改函数来记录返回值来验证这一点:

\n
const count = 0;\n\nconst a = () => {\n  // Update the document title using the browser API\n  document.title = `You clicked ${count} times`;\n}\n\nconsole.log(a());\n
Run Code Online (Sandbox Code Playgroud)\n

这打印undefined.

\n

您还可以使用console.loguseEffect函数来查看它是否也返回undefined

\n

如果您将挂钩更改为:

\n
useEffect(() => {\n  // Update the document title using the browser API\n  document.title = `You clicked ${count} times`;\n  return () => {\n    console.log(\'cleanup\');\n  }\n});\n
Run Code Online (Sandbox Code Playgroud)\n

"cleanup"每次组件重新渲染或卸载时,您都会看到该消息。您必须通过以某种方式更新组件的状态来触发重新渲染。

\n