在 useEffect 中响应两个 API 调用

问题描述 投票:0回答:1

当我在 VSCode 中按 Ctrl + S 时,我的代码在 useEffect 挂钩内有两个 API 调用,工作正常。但是,当我重新加载 Web 浏览器 (Safari) 时,只有一个 API 调用完成。为什么会出现这种情况?我没有收到任何错误响应或表明存在问题的信息。我是否误解了 useEffect 的工作原理?

import React, { useState, useContext, useEffect } from "react"
import { AccountContext } from "../../context"
....

export default function GradingAfter() {
    const context = useContext(AccountContext)
    const { token, userId } = context
    const [grading, setGrading] = useState([])
    const [beltInfo, setBeltInfo] = useState({
        belt_name: "",
        color: "" // Assuming color is directly usabl
    })
    const grading_id = 7

    useEffect(() => {
        async function fetchData() {
            try{
                const grading_response = await fetch(`/api/examination/grading/${grading_id}`, {
                    method: "GET",
                    headers: { token }
                })
                
                if (!grading_response.ok) {
                    throw new Error("Network response was not ok")
                }    
                const grading_data = await grading_response.json()
                setGrading(grading_data)
    
                const belt_response = await fetch("/api/belts/all", {
                    method: "GET",
                    headers: { token }
                })
                
                if (!belt_response.ok) {
                    throw new Error("Network response was not ok")
                }
                const belt_data = await belt_response.json()
                console.log("Belt data:", belt_data)
                
            } catch (error) {
                console.error("There was a problem with the fetch operation:", error)
            }
        }
        fetchData()
    },[])
    return(...)

reactjs
1个回答
0
投票

这个实现解决了我的问题。

const fetchGrading = () => {
    return fetch(`/api/examination/grading/${grading_id}`, {
        method: "GET",
        headers: { token }
    })
    .then(response => {
        if (!response.ok) {
            throw new Error("Network response was not ok")
        }
        return response.json()
    })
}

const fetchBelts = () => {
    return fetch("/api/belts/all", {
        method: "GET",
        headers: { token }
    })
    .then(response => {
        if (!response.ok) {
            throw new Error("Network response was not ok")
        }
        return response.json()
    })
}

useEffect(() => {
    const fetchData = async () => {
        try {
            const [grading_data, belt_data] = await Promise.all([
                fetchGrading(),
                fetchBelts()
            ])
            setGrading(grading_data)
            console.log("Grading data:", grading_data)
            updateDate(grading_data.created_at)
            const matchingBelt = belt_data.find(belt => belt.id === grading_data.belt_id)
            if (matchingBelt) {
                setBeltInfo({
                    belt_name: matchingBelt.name,
                    color: "#" + matchingBelt.color
                })
            }
        } catch (error) {
            console.error("There was a problem with the fetch operation:", error);
        }
    }
    fetchData()
}, [])
© www.soinside.com 2019 - 2024. All rights reserved.