reactjs 应用程序刚启动时无法从API获取数据

pbpqsu0x  于 2022-11-04  发布在  React
关注(0)|答案(3)|浏览(176)

我的数据是未定义的,当应用程序启动,但刷新后,数据来完美。
对于启动它给我[**未处理的承诺拒绝:TypeError:Object.entries要求输入参数不能为null或未定义]**
但在刷新后,数据完美地出现,一切正常。

*编辑

根据您的意见,我的错误有一点改变,现在我更接近解决问题,你可以检查细节。我更新了整个描述
这是我的数据的一部分

Object {
  "attributes": Object {
    "htmlName": null,
    "id": 0,
    "items": Array [
      Object {
        "htmlName": "r_1",
        "name": "m2 (Brüt)",
        "numeric": true,
        "options": Object {},
        "order": 0,
        "required": true,
      },
      Object {
        "htmlName": "r_2",
        "name": "m2 (Net)",
        "numeric": true,
        "options": Object {},
        "order": 0,
        "required": true,
      },
      Object {
        "htmlName": "r_164",
        "name": "Arsa Alanı (m2)",
        "numeric": true,
        "options": Object {},
        "order": 0,
        "required": true,
      },
      Object {
        "htmlName": "a_137",
        "name": "Oda Sayısı",
        "numeric": false,
        "options": Object {
          "12": "1+0",
          "13": "1+1",
          "14": "1.5+1",
          "15": "2+0",
          "16": "2+1",
          "17": "2.5+1",
          "18": "2+2",
          "19": "3+1",
          "20": "3.5+1",
          "21": "3+2",
          "22": "4+1",
          "226": "0+1",
          "23": "4.5+1",
          "24": "4+2",
          "25": "4+3",
          "26": "4+4",
          "27": "5+1",
          "28": "5+2",
          "29": "5+3",
          "30": "5+4",
          "31": "6+1",
          "32": "6+2",
          "33": "6+3",
          "34": "7+1",
          "35": "7+2",
          "36": "7+3",
          "37": "8+1",
          "38": "8+2",
          "39": "8+3",
          "40": "8+4",
          "41": "9+1",
          "42": "9+2",
          "43": "9+3",
          "44": "9+4",
          "45": "9+5",
          "46": "9+6",
          "47": "10+1",
          "48": "10+2",
          "49": "10 Üzeri",
        },
        "order": 0,
        "required": true,
      },

api.js

export const getData = async function (setData) {
  await axios
    .get(
      "urlblabla",
      {
        headers: {
          Authorization: `authblabla`,
        },
      }
    )
    .then((json) => {
      if (json && json.status === 200) {
        setData(json.data);
      }
    })
    .catch((e) => {
      console.log(e);
    });
};

应用程序js

const [data, setData] = useState([]);
  const [roomValue, setRoomValue] = useState(null);

  const [roomCount, setRoomCount] = useState([]);
  const [isFocus, setIsFocus] = useState(false);

  useEffect(() => {
    getDataFunc();
    setDropdown(data.attributes?.items[3].options);
  }, []);

  const getDataFunc = async () => {
    await getData(setData);
  };

  function setDropdown(query) {
    const response = query;
    try {
      const entries = Object.entries(response);
      const tempArray = [];
      for (let i = 0; i < entries.length; i++) {
        var key;
        var value;
        (key = entries[i][0]), (value = entries[i][1]);
        tempArray.push({ key: value, value: key });
      }
      setRoomCount(tempArray);
      console.log(roomCount);
    } catch (error) {
      console.log(error);
    }
  }

我该怎么解决这个问题?

hrysbysz

hrysbysz1#

我看你的data.attributesundefined的值,请你再确认一下,如果data.attributesundefined,技术上是不可能直接取数据的

v1uwarro

v1uwarro2#

看起来这个错误是由于当你试图访问attributes属性时,它是空的。但是当你一个接一个地分配它们时,它会加载,因为数据是在分配给变量之前按嵌套属性加载的。这意味着它还没有完全加载

const response = data.attributes.items[3].options;

它会输出一个错误,因为attributes未定义。所以它不是一个对象,因此attributes.items被认为是无效的

// sample

const data = {
  /* attributes: {
    items: {
      1: {
        options: 'option1'
      },
      2: {
        options: 'option2'
      },
      3: {
       options: 'option3'
      }
    }
  } */
}

const specificData = data.attributes.items[3].options

console.log(specificData) //

因此,一个解决方案是使用可选的链接操作符来避免错误,它基本上只是在您试图访问的对象之后的question mark (?)
响应将是' undefined '。这样,即使attributes为空或不为空,数据也会被分配给响应常量,然后您可以在此之外添加一些检查。

// sample

    const data = {
      /* attributes: {
        items: {
          1: {
            options: 'option1'
          },
          2: {
            options: 'option2'
          },
          3: {
           options: 'option3'
          }
        }
      } */
    }

    const specificData = data.attributes?.items[3].options

    console.log(specificData) // outputs undefined instead of an error

顺便问一下,让我知道这是否可行。也许你可以提供实际的api,或者一个api端点的例子,这样我们就可以直接测试它。或者完整的代码?
我以前遇到过这种情况,虽然我不能100%肯定这就是我所做的全部。但是对于这个错误,我确信 * 可选的链接操作符 * 可以防止它发生

neskvpey

neskvpey3#

尝试在异步函数中调用getData,并等待该过程在App.js中完成

const [data, setData] = useState([]);
const [roomCount, setRoomCount] = useState([]);

useEffect(() => {
    getDataFunc()
}, []);

const getDataFunc = async() => {
    await getData(setData);
    const response = data;
    console.log(response);
    const entries = Object.entries(response);
    const tempArray = [];
    for (let i = 0; i < entries.length; i++) {
      var key;
      var value;
      (key = entries[i][0]), (value = entries[i][1]);
      tempArray.push({ key: value, value: key });
    }

    setRoomCount(tempArray);
    console.log(roomCount);
}

注意:最佳实践不是直接将setData函数传递给getData api调用,而是从api返回响应,并在主代码中分配响应,如下所示

const response = await getData();
setData(response)

相关问题