简体   繁体   English

react - 如何使钩子异步

[英]react - how to make hook async

This is my component.这是我的组件。

const DashboardContext = React.createContext()

function DashboardStateProvider({ children }) {
    const Provider = DashboardContext.Provider
    return (
      <WithSubscription Provider={Provider} connectedAccount={wallet.account}>
        {children}
      </WithSubscription>
    )
}

async function WithSubscription({ Provider, connectedAccount, children }) {
  const { data } =  await asyncCallHere()

  return ( <Provider value={{ treasury }}> {children} </Provider> )
}

function useDashboardState() {
  return useContext(DashboardContext)
}

export { DashboardStateProvider, useDashboardState }

In the code, one can see asyncCallHere .在代码中,可以看到asyncCallHere Before this code, asyncCallHere was synchronous which means I had no mistake in the code.在这段代码之前, asyncCallHere是同步的,这意味着我在代码中没有错误。 But I need it to make async, so I had to add async to withSubscription function.但是我需要它来进行异步,所以我必须将async添加到withSubscription function。 Hope the code makes sense.希望代码有意义。

The problem is that because I put await and async there, it results in the following error:问题是因为我把awaitasync放在那里,它会导致以下错误:

Unhandled Rejection (Error): Invalid hook call.未处理的拒绝(错误):无效的挂钩调用。 Hooks can only be called inside of the body of a function component.钩子只能在 function 组件的主体内部调用。 This could happen for one of the following reasons:这可能由于以下原因之一而发生:

  1. You might have mismatching versions of React and the renderer (such as React DOM)你可能有不匹配的 React 版本和渲染器(例如 React DOM)
  2. You might be breaking the Rules of Hooks您可能违反了 Hooks 规则
  3. You might have more than one copy of React in the same app See facebook dev page for tips about how to debug and fix this problem.您可能在同一个应用程序中拥有多个 React 副本,请参阅 facebook 开发页面以获取有关如何调试和修复此问题的提示。

I'd appreciate the quick answer to fix this, due to the fact that I am not react developer and I don't intend to understand what's happening there in deep other than to fix it.我很感激能快速解决这个问题,因为我不是反应开发人员,除了修复它之外,我不打算深入了解那里发生的事情。

Hooks cannot be async.钩子不能是异步的。

You always need to return sync data from the hook.你总是需要从钩子返回同步数据。

However, if you want to do some async operation inside the hook, you can do it inside useEffect to store the data in the hook state and return that data from the hook itself.但是,如果您想在钩子内部进行一些异步操作,您可以在 useEffect 内部进行,以将数据存储在钩子 state 中并从钩子本身返回该数据。

import React, {useEffect, useState} from 'react'

function useAsyncCallHere() {
  const [data, setData] = useState(null)

  useEffect(() => {
    async function getData() {
      const response = await asyncCallHere()
      setData(response.data)
    }

    getData()
  }, [])

  return data
}

function WithSubscription({ Provider, connectedAccount, children }) {
  const data = useAsyncCallHere()

  return ( <Provider value={{ data }}> {children} </Provider> )
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM