首页 > 解决方案 > 在加载时反应渲染,但在异步调用完成时不更新

问题描述

*我遇到了一些组件不显示信息的问题,因为在渲染发生之前没有实现异步承诺。我确信这只是一些简单的事情,但我不知道用谷歌 atm 搜索什么;)

我只是通过 axios 对一个 api.get 使用 async-await,并且承诺已经实现,只是在呈现网站之前没有。我也试过 useEffect(() => {},[]); 但我的目标是在没有任何点击的情况下加载网站并准备好所有信息。

我希望这是有道理的!如果您有时间看,再次感谢您,如果有任何遗漏,请发表评论。

谢谢!*

组件:

import React, { useEffect, useState } from 'react';
import getServiceDetails from '../../controller/getServiceInfo';

function Customer(props) {
  const [serviceButtons, setServiceButtons] = useState([]);

  // here I get the axios async call \/\/
  const serviceInfo = getServiceDetails();
  // it returns the promise unfullfilled on render.

  if (typeof serviceInfo !== 'undefined' && serviceInfo.length > 0) {
    let buttonArray = [];
    for (let i = 0; i < serviceInfo.length; i++) {
      buttonArray.push(
        <button
          onClick={() => {
            console.log('test');
          }}
          key={i}
        >
          {serviceInfo[i].name}
        </button>
      );
    }
    setServiceButtons(buttonArray);
  }

  return (
    <div id="customer_card">
      <h2>Customer overview:</h2>
      <p>
        Name: {props.db?.firstname + ' ' + props.db?.lastname} <br />
        Phone: {props.db?.phone} <br />
        Email: {props.db?.email}
      </p>
      <div className="newbookingbuttons">
        <h3>New reservations:</h3>
        {serviceButtons}
      </div>
      <div className="list_of_bookings">
        <h3>Current bookings:</h3>
        <p>
          Here we list all bookings that are current with possible changes
          <button
            onClick={() => {
              // this button does not work... (tried to check if it was different with a click)
              let buttonArray = [];
              for (let i = 0; i < serviceInfo.length; i++) {
                buttonArray.push(
                  <button
                    onClick={() => {
                      console.log('test');
                    }}
                    key={i}
                  >
                    {serviceInfo[i].name}
                  </button>
                );
              }
              setServiceButtons(buttonArray);
            }}
          >
            Manual
          </button>
        </p>
      </div>
    </div>
  );
}

export default Customer;

安慰:

Promise {<pending>}Customer.js:29 undefined
Customer.js:30 []
Customer.js:28 Promise {<pending>}__proto__: Promise[[PromiseState]]: "fulfilled"[[PromiseResult]]: Array(1)
Customer.js:29 undefined

标签: javascriptreactjsasynchronous

解决方案


推荐阅读