javascript - 在加载时反应渲染,但在异步调用完成时不更新
问题描述
*我遇到了一些组件不显示信息的问题,因为在渲染发生之前没有实现异步承诺。我确信这只是一些简单的事情,但我不知道用谷歌 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
解决方案
推荐阅读
- unity3d - 如何正确使用 UNET
- ssas - 在 PowerBI 中合并来自多个 SSAS 多维数据集的数据
- wagtail - 如何迭代模板中的“页面”对象的属性?
- python - 图中的强连接组件 - networkx 库
- android - Android 应用在 onClickListener 上崩溃
- amazon-web-services - 当第一个实例达到 85% 的内存或 cpu 时,启动第二个实例 AWS,
- javascript - Firebase 云消息传递 - Django - 我如何为工作人员提供服务?
- php - PHP 5.6、xDebug、远程调试设置
- r - 使用较大数据集的索引值为数据框中的 NA 值创建指示变量
- bash - 如果仅向用户显示 COMPREPLY bash 完成选项的子字符串,则不要替换先前的输入