如何在继续之前等待 Fetch 完成抓取数据

时间:2021-03-23 19:20:17

标签: javascript reactjs promise

我想弄清楚如何使用 FetchAPI 从 URL 获取数据并将其显示在我的页面上。数据是一个学生列表,但是我相信因为它是异步的,我的页面尝试在不完整的数据上呈现我的迭代循环,因此它抛出一个错误,说我的变量不可迭代(应该是)。这是我的代码的样子

function StudentDisplay(){

    const user = "URL that I won't disclose but it works as it should be";
    fetch(user)
    .then(res => res.json())
    .then(data=> DisplayStudents(data.students));

    const DisplayStudents = students => {
        console.log("blah");
        console.log(students);
        let result = []
        students.forEach(student => {
            console.log(student);
            const studentElement = <>Hello World</>;
            result.push(studentElement);
        })
        return <span>{result}</span>
    }

    return(
        <DisplayStudents/>
    );
}

这是我的控制台在尝试打印内容时的样子:

blah
{}
blah //I don't quite understand why this is printing twice
{}
//Long Error complaining that 'students.forEach' is not a function and some other stuff
blah
[Array]
Student object
Student object
...
blah // Again I don't quite understand why it gets printed twice
blah
[Array]
Student object
Student object
...

我也试过 xhr 和 axios,但我真的不明白这些是如何工作的,因为它们都给出了类似的错误,所以我想坚持使用 fetch。有人可以解释一下发生了什么,我如何才能让它发挥作用?

3 个答案:

答案 0 :(得分:1)

短期内,您应该以某种方式隔离 API 请求并将结果存储在适当的位置。 有多种方法可以做到这一点,但基本的和现代的方法可能是使用钩子:

import {useState, useEffect} from 'react'
const user = 'URL that i won't disclose but it works as it should be';

function StudentDisplay(){
    const [students, setStudents] = useState([])
    
    useEffect(() => {
      fetch(user)
        .then(res => res.json())
        .then(students => setStudents(students));
    }, [])


    return(
        <ul>
          {students.map(s => <li key={s.id}>{s.name}</li>)}
        </ul>
    );
}

您可以在此处找到有关钩子的更多信息https://reactjs.org/docs/hooks-faq.html

答案 1 :(得分:0)

您可以通过在函数前面写入 async 关键字来使函数异步,并将结果存储在类似 -=0.5 的变量中(也省略 .then)

答案 2 :(得分:0)

Students 在您的响应对象中。你不是试图循环它,而是响应对象,这就是你收到错误的原因。你可以

fetch(user)
    .then(res => res.json())
    .then(({students}) => DisplayStudents(students));

或在您的 DisplayStudents

const DisplayStudents = resp => {
        console.log("blah");
        console.log(resp);
        let result = []
        resp.students.forEach(student => {
            console.log(student);
            const studentElement = <>Hello World</>;
            result.push(studentElement);
        })
        return <span>{result}</span>
    }