没有承诺地从 json url 填充数组变量

populate array variable from json url without promise

你好,我试图通过将所有数据输入数组变量来显示 ReactJS 中 json url 的数据,但我不能在 JSX 部分使用数组,因为渲染时数组尚未填充我尝试了很多东西,但我总是以一个承诺循环结束,我需要一个承诺从另一个获取数据。 代码:

let arry = [];
  let ar = [];

  async function getdriver() {
    const response = await fetch("https://ergast.com/api/f1/current/drivers.json");
    ar = await response.json();
    ar.MRData.DriverTable.Drivers.forEach((element) => {
      arry.push(element);
    });
    return arry;
  }

  getdriver();

  console.log(arry);// the array is populated but i think it waits for it before showing
  console.log(arry.lenght); //lenght is 0

JSX:

return (
    <div>
      <Menu />
      <div style={{ textAlign: "left" }}>
        <h4>ff</h4>
        <Button >change</Button>
        <br></br>
        <i>{arry[0].code}</i>// error ' Cannot read property 'code' of undefined ' so arry is empty? 
      </div>
    </div>
  );

获取数据是一个副作用,然后您需要将此数据存储为 state, so you will need to make use of two kinds of hooks (assuming you are creating function components):

您的异步代码将在 useEffect 中调用,调用完成后您将使用 useState.

将结果保存为组件的状态

代码将类似于下面的示例(我尽可能多地保留了您的代码,但重命名了一些函数和变量,并添加了一些注释,以尽可能对其他读者有用):

import { useState, useEffect } from "react";

// this can exist outside the component
// it can even be in a different file
async function fetchDrivers() {
  const response = await fetch(
    "https://ergast.com/api/f1/current/drivers.json"
  );
  const data = await response.json();
  return data.MRData.DriverTable.Drivers;
}

function YourComponent() {
  // we declare the state, initially it's an empty array
  const [drivers, setDrivers] = useState([]);

  // we declare the effect that runs exactly once,
  // when the component is mounted
  useEffect(() => {
    fetchDrivers().then(setDrivers);
  }, []);

  // we print the code for all drivers
  // mapping the drivers array to JSX.
  // notice the key attribute, this is required with map
  // to uniquely identify each element
  return (
    <div>
      <Menu />
      <div style={{ textAlign: "left" }}>
        <h4>ff</h4>
        <Button>change</Button>
        <br></br>
        {drivers.map((driver, index) => (
          <p key={index}>
            <i>{driver.code}</i>
          </p>
        ))}
      </div>
    </div>
  );
}

当您想在第一次渲染时显示从 API 获取的数据时,您应该将 API 调用放入 useEffect 并提供一个空数组作为对 useEffect 同时将数组设置为状态值 例如:

 import {useState, useEffect} from 'React';

 function YourComponent(){
  const [array, setArray] = useState([]);

  useEffect(()=>{getDriver().then((array)=>
  {setArray(array)})}
  ,[])
 }

这只是一个示例,在 getDriver() 中,在您获得 API 调用的结果后,您应该使用 setState() 设置 array 来告诉 React 重新在该值更改后渲染,但在这里当你把它放在 useEffect 中时,它只会在第一次渲染时触发。