Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
186 views
in Technique[技术] by (71.8m points)

reactjs - Getting error when using async function with react hooks

I am getting following error when I testing hooks with async function;

Invariant Violation Objects are not valid as a React child (found: [object Promise]).

async function Test () {
  const data = await fetch('https://jsonplaceholder.typicode.com/posts/42');
  const json = await data.json();  
  const id = json.id;
  return id;
}

...

function App() {
  return (
    <div className="App">
      <h1>React Hooks Example</h1>

      <Suspense fallback={<LoadingMessage />}>
        <Test />
      </Suspense>

    </div>
  );
}

https://codesandbox.io/s/4w2yzvyro7

How can I fix this error

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

<Suspense> is supposed to be used in very specific manner. It suspends the rendering of lazy components and renders other kinds of components as is.

Test is not lazy component but async function, it returns promise object and not React element, hence Test is not a valid React component.

lazy components are aimed at rendering default imports from lazily loaded components. Basically lazy component should return a promise of an object with default property that contains valid React component.

It can be used as:

const Test = lazy(async () => {
  const data = await fetch('https://jsonplaceholder.typicode.com/posts/42');
  const json = await data.json();  
  const id = json.id;

  return { default: (props) => <div>{id}</div> };
});

...

<Suspense fallback={<LoadingMessage />}>
  <Test />
</Suspense>

Notice that due to its primary use case, lazy component can't accept parameters, if Test had props, they would be passed to a component that async function returns.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...