在 Promise 完成后使用 JSX 反应变量

using a JSX react variable after completion of a Promise

代码如下:

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 {}中,代码是同步的。因此,在导致错误的承诺完成之前 运行s。我要运行之后就答应了。如何解决这个问题?提前致谢。

您需要将调用移动到组件内部并使用 useEffectuseState,或者在组件内部进行轮询。

const Stats = () => {
 const [data, setData] = useState([])

 useEffect( () => {
  const promiseHandle = async () => {
    setData(await init());
  };
  promiseHandle();
 }, [])