這是代碼:
import React from 'react';
import { Link } from 'react-router-dom';
import Main from '../layouts/Main';
import Cell from '../components/Stats/nCell';
import init from '../data/stats';
const promiseHandle = async () => {
Window.data = await init();
};
promiseHandle();
const Stats = () => (
<Main
title="Stats"
description="Some statistics about Ahammad Shawki and ahammadshawki8.github.io"
>
<article className="post" id="stats">
<header>
<div className="title">
<h2 data-testid="heading"><Link to="/stats">Publications</Link></h2>
</div>
</header>
<p className="rec-p"> Please accept my sincere apologies for the inconvenience.
At the moment, I am working on my Publication API for this website
so may not be able to find all of my articles here.
But the great news is that you can always read all of my articles on <a href="https://ahammadshawki8.hashnode.dev/">HashNode</a>.
</p>
</article>
{Window.data.map((post) => (
<Cell
data={post}
key={post.title}
/>
))}
</Main>
);
export default Stats;
由于我正在使用promise,因此此處Window.data已被宣告為異步方式。但是在 react JSX {}中,代碼是同步的。因此,它在導致錯誤的承諾完成之前運行。我想在承諾之后運行它。如何解決這個問題?提前致謝。
uj5u.com熱心網友回復:
您需要在組件內移動呼叫并在組件內使用useEffect和useState或進行輪詢。
const Stats = () => {
const [data, setData] = useState([])
useEffect( () => {
const promiseHandle = async () => {
setData(await init());
};
promiseHandle();
}, [])
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/462296.html
標籤:javascript 反应 异步 异步等待 承诺
上一篇:JavaScript:我們可以創建什么型別的函式來異步執行?
下一篇:從陣列回傳資料失敗
