【发布时间】:2021-05-21 12:44:21
【问题描述】:
我正在尝试从 Json 中提取深层数据,但是当我导航到屏幕时,我的代码会执行第一个承诺,但第二个承诺会映射到我在之前设置的钩子中承诺。我试图弄清楚如何仅在第一个承诺得到解决时才执行第二个承诺。 这是我的代码:
const [tableHead, setTableHead] = useState('');
const [performance, setPerformance] = useState('');
const [performanceKpis, setPerformanceKpis] = useState('');
useEffect(() => {
async function getKpis() {
const findData = await Promise.all(
json.map((performance) => performance.performance)
);
setPerformance(...findData);
const findValues = await Promise.all( <=============== This is the stuff
setPerformanceKpis(performance.map((performance) => performance.value))
);
// setPerformanceKpis(findValues);
};
getKpis()
}, []);
我对 Promise 很陌生。我没有弄清楚它是如何正常工作的。
[
{
"id": "3c20fbe3-fc59-433d-b349-6aa3b4a4c17b",
"name": "20210504",
"external_id": "3ad0c67e-170c-4ea8-afcc-850c94f449aa",
"farm_id": "489cd6a6-db19-4a6f-bc95-1d981edc972f",
"farm_name": "Granja Presence",
"producer_id": null,
"producer_name": "Produtor Granja Presence",
"type": "limited",
"finished": true,
"walkthrough_available": false,
"performance": [
{
"key": "AVERAGE_DATE_INPUT",
"name": null,
"abbreviation": null,
"value": "2021-05-04T00:00:00",
"measurement_unit": "date",
"decimal_places": null,
"is_critical": false
},
{
"key": "AVERAGE_DATE_OUTPUT",
"name": null,
"abbreviation": null,
"value": "2021-05-04T00:00:00",
"measurement_unit": "date",
"decimal_places": null,
"is_critical": false
},
这是我的 JSON 结构,我想提取性能数组中的对象。所以我制作了一张地图并将数据推送到我的 Hook,现在我正在尝试在我的 Performance 数组中进行映射并将对象推送到我的 Hook,稍后我将在表格中呈现。
【问题讨论】:
-
根据代码,您将映射结果
performance作为参数发送到setPerformanceKpis。如果performances应该在setPerformancesKpis之后执行,您需要链接它们。我在 MDN(链接)上了解了 Promise,您可以在其中学习使用.then链接 Promise。Promise.all仅在您想同时执行所有承诺时使用。 developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… -
json是什么,它从何而来?为什么里面有承诺?我认为这里没有发生任何异步操作,您可能甚至不需要 Promise。 -
setPerformance只有一个参数,您可能不想对调用使用展开语法。 -
您需要使用
findData.map(…),而不是performance.map(…)。注意setPerformance没有分配给performance常量! -
您的代码看起来有点奇怪。我认为
Promise.all不是您正在寻找的方法。您能否添加更多示例来解释您要完成的工作?
标签: javascript react-native react-hooks