0

嗨,我正在尝试通过将所有数据输入到数组变量中来显示来自 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>
  );
4

2 回答 2

0

获取数据是一个副作用,然后您需要将此数据存储为state,因此您需要使用两种钩子(假设您正在创建函数组件):

您的异步代码将被调用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>
  );
}
于 2021-07-23T11:06:36.097 回答
0

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

 import {useState, useEffect} from 'React';

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

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

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

于 2021-07-23T11:06:40.323 回答