【发布时间】:2020-12-07 21:57:18
【问题描述】:
总的来说,我对 JavaScript/React 非常陌生,并且在 Promise 和 async 的概念上苦苦挣扎。
首先我有getSimById,这是一个JS文件中的API调用,它返回一个Promise:
export function getSimById(simId) {
return fetch(simsUrl + "/results/" + simId, {
method: "GET",
headers: new Headers({
Authorization: "Basic " + base64.encode(login + ":" + password)
})
})
.then(handleResponse)
.catch(handleError);
}
而handleResponse 是一个异步函数。
export async function handleResponse(response) {
if (response.ok) {
let someResponse = response.json();
return someResponse;
}
if (response.status === 400) {
throw new Error(error);
}
const error = await response.text();
throw new Error("Network response was not ok.");
}
现在我有一个返回 Table 的功能组件:
import React, { useState, useEffect } from "react";
import { getSimById } from "../api/outrightSimulatorApi";
function SimulationReport(props) {
const location = useLocation();
const [simResult, setSimResult] = useState([]);
useEffect(() => {
getSimById(location.state.simId).then(result => setSimResult(result));
}, []);
let reformattedData = getSimById(location.state.simId).then(
data => reformattedData = data?.markets?.length ? data.markets.reduce(
(accumulator, market) =>
market.selections.map(({ name, probability }, index) => ({
...accumulator[index],
"Team name": name,
[market.name]: probability,
})),
[],
) : null);
return (
<div>
<Table striped bordered hover size="sm" responsive>
<thead>
<tr>{
}
</tr>
</thead>
<tbody>{
}
</tbody>
</Table>
</div>
);
在这段代码中,我想将reformattedData 映射为一个数组,并最终将其值映射到返回的Table 中。但是,reformattedData 在此实例中不是数组,实际上是Promise。因此,每当我尝试访问reformattedData[0] 之类的内容时,它实际上会返回undefined,并且我无法映射Table 中的值。在这种情况下,如何将 Promise 分配给变量,以便对其执行操作?
【问题讨论】:
-
您需要映射
simResult数组,而不是为getSimById调用reformattedData。通过在then之后添加catch,确保在useEffect中正确处理错误。 -
你为什么在两个不同的地方打电话给
getSimById?您应该只在useEffect回调中执行此操作,而不是在组件函数中内联。
标签: javascript json reactjs promise optional-chaining