React Query useQuery 无法读取未定义的属性数据

时间:2021-02-01 16:20:41

标签: javascript reactjs

这是我在 codepan 中的代码:https://codesandbox.io/s/relaxed-drake-4juxg?file=/src/Persons/persons.jsx

我不知道为什么它有时在读取未定义的属性数据时会抛出无法读取未定义属性数据的错误!

我在我的公共文件夹中创建了一个 json 文件:

[
  {
    "id": 0,
    "name": "John",
    "lastName": "Doe",
    "address": "Main Street",
    "gender": "male",
    "country": "USA",
    "city": "LA"
  },
  {
    "id": 1,
    "name": "Michael",
    "lastName": "Zeburgee",
    "address": "Second Street",
    "gender": "male",
    "country": "Germany",
    "city": "Hamburg"
  },
  {
    "id": 3,
    "name": "Julia",
    "lastName": "Hleb",
    "address": "St.Patric",
    "gender": "female",
    "country": "Belarus",
    "city": "Minsk"
  },
  {
    "id": 4,
    "name": "Petar",
    "lastName": "Pan",
    "address": "Some Street",
    "gender": "male",
    "country": "UK",
    "city": "London"
  }
]

我有一个 axios 请求:

import axios from "axios";

export default async function getPersonsInfo() {
  const response = await axios.get("persons.json");
  return response;
}

有一个 Persons 组件:

import React, { useState } from "react";
import { useQuery } from "react-query";
import getPersonsInfo from "../api/personCalls";

export default function Persons() {
  const [persons, setPersons] = useState([]);
  const { data: personsData, status } = useQuery(
    "personsData",
    getPersonsInfo,
    {
      onSuccess: () => {
        setPersons(personsData.data);
      },
      onError: (error) => {
        console.log(error);
      }
    }
  );

  return (
    <>
      {status === "loading" ? (
        <div>Loading ... </div>
      ) : (
        <div>
          {persons.map((person) => (
            <div>
              <p>{person.name}</p>
              <p>{person.lastName}</p>
              <p>{person.address}</p>
              <p>{person.gender}</p>
              <p>{person.country}</p>
              <p>{person.city}</p>
            </div>
          ))}
        </div>
      )}
    </>
  );
}

问题是它无法读取数据,但是如果我 console.log(personsData) 有数据。

onSuccess: () => {
        setPersons(personsData.data);
      },

您可以在代码盘中看到。首先,当您打开文件时,它正在加载...并获取数据,但是一旦您刷新页面,它就不能!

1 个答案:

答案 0 :(得分:1)

只需从 onSuccess 回调中获取数据:

onSuccess: (data) => {
        console.log('data',data)

查看记录的数据,然后使用 setPersons 将您需要的数据设置为状态。