0

私は一般的に 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]このため、実際に を返すようなものにアクセスしようとするとundefinedTable. この場合、Promise を変数に割り当てて操作を実行するにはどうすればよいですか?

4

3 に答える 3