首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Preact错误:在根组件中使用异步等待时,“对象作为子对象无效。遇到带有键{}的对象”

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

Stack Overflow用户
提问于 2020-09-19 16:14:34
回答 2查看 984关注 0票数 3

我第一次用Preact。

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

app.js中,我试图使用以下代码:

代码语言:javascript
复制
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;

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

代码语言:javascript
复制
Uncaught Error: Objects are not valid as a child. Encountered an object with the keys {}.

为什么?

如果我不使用async/await,它就能工作。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-09-19 17:55:33

免责声明:我在Preact工作。

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

代码语言:javascript
复制
const invalidVNode = { foo: 123 };
<div>{invalidVNode}</div>

在您的示例中,组件函数返回一个Promise,它是JavaScript中的一个对象。当Preact呈现该组件时,render函数将不会返回vnode,而是返回允诺。这就是错误发生的原因。

这就提出了一个问题:

如何进行异步初始化?

一旦触发,Preact中的呈现过程总是同步的。返回Promise的组件破坏了该约定。之所以出现这种情况,是因为您通常希望在异步初始化发生时,至少向用户显示一些内容,比如旋转器。一个真实的场景就是通过网络获取数据。

代码语言:javascript
复制
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>
  )
}
票数 6
EN

Stack Overflow用户

发布于 2020-09-19 16:25:20

Reactjs是一个组件库。在核心,它有一个功能,如

代码语言:javascript
复制
React.createElement(component, props, ...children)

这里,第一个参数是要呈现的组件。

当您放置await sleep(3000)时,函数不是返回任何有效的子/html对象,而是返回一个空对象。这就是为什么你要得到这个错误。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63970864

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档