【问题标题】:Do React hooks need to return a value?React 钩子需要返回一个值吗?
【发布时间】:2020-09-20 16:39:58
【问题描述】:

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

例子:

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


// functional component
export function Details() {
  useSetup()

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

【问题讨论】:

  • 你想用 react hooks 实现 redux 吗?
  • 是否有可能因为if (data)而导致钩子无法获取?
  • 如果一个钩子需要返回任何东西,它通常会被记录。 useEffect 是一个很好的钩子示例,它可能不会返回任何内容(如果它返回,它就是一个效果清理函数)。 Hooks 可以返回任何必要/需要/等等...毕竟它们只是函数(有一些使用规则)。
  • 应该使用 useReducer 来实现类似状态管理系统的 redux
  • @DrewReese 对!好的,谢谢你帮我解决这个问题。现在这很有意义。

标签: javascript reactjs redux react-hooks


【解决方案1】:

是的,您的方法是正确的。 React 钩子不需要返回任何东西。 React documentation 声明:

我们不必从效果中返回命名函数。我们称之为 cleanup here 以澄清其目的,但您可以返回一个箭头 函数或称它为不同的名称。

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

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

const [count, setCount] = useState(0);

// Similar to componentDidMount and componentDidUpdate:
useEffect(() => {
  // Update the document title using the browser API
  document.title = `You clicked ${count} times`;
});

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

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

const count = 0;

const a = () => {
  // Update the document title using the browser API
  document.title = `You clicked ${count} times`;
}

console.log(a());

这打印出undefined

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

如果你把钩子改成这样:

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

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

【讨论】:

    猜你喜欢
    • 2019-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-22
    • 1970-01-01
    • 2022-06-23
    • 1970-01-01
    相关资源
    最近更新 更多