use
是一个用于解析 React v18 及以下版本的 promise 状态的 polyfill hook。请注意,它只实现了消费 promise 的能力。
参考资料
https://www.reactuse.com/zh-Hans/state/use
https://zh-hans.react.dev/reference/react/use#dealing-with-rejected-promises
app.jsx
import { useState, Suspense, lazy } from 'react';
const Son = lazy(() => delayForDemo(import('./Son.jsx')));
function fn1() {
return new Promise((res) => {
setTimeout(res, 1000, { a: { b: 33 } })
})
}
async function fn2() {
var res = await new Promise((res) => {
setTimeout(res, 1000, 'bbbb')
})
return res
}
export default function MarkdownEditor() {
const [dt1, sets] = useState(fn1);
const [dt2, setb] = useState(fn2);
return (
<>
<Suspense fallback={<div>loading...</div>}>
<h2>Preview</h2>
<Son dt1={dt1} dt2={dt2} />
</Suspense>
</>
);
}
// Add a fixed delay so you can see the loading state
function delayForDemo(promise) {
return new Promise(resolve => {
setTimeout(resolve, 1200);
}).then(() => promise);
}
son.jsx
import { use } from 'react'
export default function MarkdownPreview({ dt1, dt2 }) {
var d1 = use(dt1)
var d2 = use(dt2)
return (
<>
<h1>{dt1.a.b}</h1>
<div>-------</div>
<h1>{d2}</h1>
</>
);
}
只有等待fn1,fn2里的函数 resolve之后,才会显示Son组件
附:延迟promise时间
延迟特定promise时间
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
delay(3000).then(() => alert('runs after 3 seconds'));
附:延迟组件加载时间
//定义
function delayForComp(promise) {
return new Promise(resolve => {
setTimeout(resolve, 1200);
}).then(() => promise);
}
//使用:
import { useState, Suspense, lazy } from 'react';
const Mxxxxx = lazy(() => delayForComp(import('./Mxxxxx.jsx')));
//放在Suspense内部
return (
<>
<Suspense fallback={<div>loading...</div>}>
<h2>Preview</h2>
<Mxxxxx dt1={dt1} dt2={dt2} />
</Suspense>
</>
);