我第一次用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;但不幸的是,浏览器给了我错误:
Uncaught Error: Objects are not valid as a child. Encountered an object with the keys {}.为什么?
如果我不使用async/await,它就能工作。
发布于 2020-09-19 17:55:33
免责声明:我在Preact工作。
当一个无效的对象作为不匹配预期的h/createElement返回类型(通常称为vnode )的子对象传递时,我们的调试插件( debug addon )将打印此错误
const invalidVNode = { foo: 123 };
<div>{invalidVNode}</div>在您的示例中,组件函数返回一个Promise,它是JavaScript中的一个对象。当Preact呈现该组件时,render函数将不会返回vnode,而是返回允诺。这就是错误发生的原因。
这就提出了一个问题:
如何进行异步初始化?
一旦触发,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>
)
}发布于 2020-09-19 16:25:20
Reactjs是一个组件库。在核心,它有一个功能,如
React.createElement(component, props, ...children)这里,第一个参数是要呈现的组件。
当您放置await sleep(3000)时,函数不是返回任何有效的子/html对象,而是返回一个空对象。这就是为什么你要得到这个错误。
https://stackoverflow.com/questions/63970864
复制相似问题