反应:更新 useEffect 钩子中的状态

时间:2021-07-14 11:53:08

标签: javascript reactjs react-hooks

我相信这是相当简单的,但由于某种原因,经过相当多的 google 后,我无法找到答案:/

我在下面有一个简单的组件,它从我的 Spring Boot 应用程序中获取一些数据并将其转换为 JSON 承诺。

  1. 我不确定是否允许我使用 Promise 设置状态,或者我是否必须在这样做之前通过其他方法解析它?调用 visitDetailssetVisitDetails 的状态保持为空。

  2. 如何使用 map 函数来引用响应中的变量?

组件

import { useEffect, useState } from "react";

const QrCodeDisplay = () => {
  
    const urlParams = new URLSearchParams(window.location.search);
    const qrId = urlParams.get('qrCode');
    const fetchQrURL = 'http://localhost:8080/api/qr-code/'+qrId;
    const [visitDetails, setVisitDetails] = useState([]);
    const fetchVisitURL = 'http://localhost:8080/api/visit-by-qrcodeid/'+qrId;

    useEffect(()=> {

       
        console.log(fetchVisitURL);
        
        const fetchVisitDetail = async () => {
            try{
                const res = await fetch(fetchVisitURL,{
                    method: 'GET',
                    headers: {
                        'Content-type': 'application/json',
                    },
                });
                const jsonResponse = res.json();
                console.log(jsonResponse);
                setVisitDetails(jsonResponse);
                
            
            }catch(error){
                console.log("error", error);
            }
        };
        fetchVisitDetail();
        
    },[fetchVisitURL]);

    return (
        <div>
            <h2>Your QR entry pass</h2>
            <h3>Start Date of Visit:</h3>
            <img src={fetchQrURL} alt="QR entry" width="200px" height="200px"></img>
        </div>
    )
}

export default QrCodeDisplay

来自后端的 JSON(API 通过 Postman 工作,React 组件返回 promise 为成功)

[
    {
        "scheduledVisitId": 1,
        "visitorId": 2,
        "startDateOfVisit": "2021-01-18",
        "endDateOfVisit": "2021-01-19",
        "qrCodeId": "c4ca4238a0b923820dcc509a6f75849b",
        "valid": true,
        "oneTimeUse": false,
        "raisedBy": 123456
    }
]

1 个答案:

答案 0 :(得分:1)

你在 res.json() 之前错过了 await

    useEffect(()=> {

       
        console.log(fetchVisitURL);
        
        const fetchVisitDetail = async () => {
            try{
                const res = await fetch(fetchVisitURL,{
                    method: 'GET',
                    headers: {
                        'Content-type': 'application/json',
                    },
                });
                const jsonResponse = await res.json();
                console.log(jsonResponse);
                setVisitDetails(jsonResponse);
                
            
            }catch(error){
                console.log("error", error);
            }
        };
        fetchVisitDetail();
        
    },[fetchVisitURL]);
    ```