Preact 错误:“对象作为子对象无效。在根组件中使用异步等待时遇到带有键 {} 的对象”

Fre*_*ors 2 javascript reactjs react-router preact preact-router

我是第一次使用 Preact。

我只是用 preact-cli 和这个默认模板创建了一个新项目:https : //github.com/preactjs-templates/default

app.js我尝试使用此代码时:

import { Router } from 'preact-router';

import Header from './header';
import Home from '../routes/home';
import Profile from '../routes/profile';

// I added this function
function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

const App = async () => { // I added "async" and the "{" in this line
  await sleep(3000) // I added this line

  return ( // I added this line
    <div id="app">
      <Header />
      <Router>
        <Home path="/" />
        <Profile path="/profile/" user="me" />
        <Profile path="/profile/:user" />
      </Router>
    </div>
  )
} // I added this line

export default App;
Run Code Online (Sandbox Code Playgroud)

但不幸的是浏览器给了我错误:

Uncaught Error: Objects are not valid as a child. Encountered an object with the keys {}.
Run Code Online (Sandbox Code Playgroud)

为什么?

如果我不使用async/await.

mar*_*ter 5

免责声明:我在 Preact 上工作。

preact/debug每当无效对象作为与 的预期返回类型不匹配的子对象传递时,我们的调试插件 ( ) 将打印此错误h/createElement,通常称为vnode

const invalidVNode = { foo: 123 };
<div>{invalidVNode}</div>
Run Code Online (Sandbox Code Playgroud)

在您的情况下,您的组件函数返回一个PromiseJavaScript 对象。当 Preact 渲染那个组件时,渲染函数不会返回一个vnode,而是一个 Promise 。这就是错误发生的原因。

这提出了一个问题:

如何进行异步初始化?

一旦触发,Preact 中的渲染过程始终是同步的。返回的组件Promise违反了合同。这样做的原因是因为您通常希望在异步初始化发生时至少向用户显示一些东西,例如微调器。例如,一个真实的场景是通过网络获取数据。

import { useEffect } from "preact/hooks";

const App = () => {
  // useEffect Hook is perfect for any sort of initialization code.
  // The second parameter is for checking when the effect should re-run.
  // We only want to initialize once when the component is created so we
  // pass an empty array so that nothing will be dirty checked.
  useEffect(() => {
    doSometThingAsyncHere()
  }, []);

  return (
    <div id="app">
      <Header />
      <Router>
        <Home path="/" />
        <Profile path="/profile/" user="me" />
        <Profile path="/profile/:user" />
      </Router>
    </div>
  )
}
Run Code Online (Sandbox Code Playgroud)