首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在承诺完成后使用completion变量

在承诺完成后使用completion变量
EN

Stack Overflow用户
提问于 2022-04-18 09:30:29
回答 1查看 43关注 0票数 0

以下是代码:

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

由于我使用的是一个承诺,在这里,Window.data已经被声明为异步方式。但是在react JSX {}中,代码是同步的。因此,它在完成导致错误的承诺之前运行。我想履行诺言。如何解决这个问题?提前谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-04-18 09:41:45

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

代码语言:javascript
复制
const Stats = () => {
 const [data, setData] = useState([])

 useEffect( () => {
  const promiseHandle = async () => {
    setData(await init());
  };
  promiseHandle();
 }, [])
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71909995

复制
相关文章

相似问题

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