簡體   English   中英

為什么我在使用 useState 作為數組時出現錯誤

[英]why i am getting an error while i am using useState as an array

import axios from "axios";
import { useEffect, useState } from "react";
import "./styles.css";
export default function App() {
  const [userDataInfo, setUserDataInfo] = useState([]);
  const fetchData = () => {
    axios
      .get("https://random-data-api.com/api/address/random_address")
      .then(function (response) {
        // console.log(response.data);
        return JSON.stringify(response);
      })
      .then(function (data) {
        setUserDataInfo(data);
      });
  };
  useEffect(() => {
    fetchData();
  }, [userDataInfo]);
  return (
    <div className="App">
      {userDataInfo.map((data) => (
        <p>{}</p>
      ))}
    </div>
  );
}
TypeError
userDataInfo.map is not a function
App
/src/App.js:26:20
  23 | 
  24 | return (
  25 |   <div className="App">
> 26 |     {userDataInfo.map((data) => (
     |                  ^
  27 |       <p>{}</p>
  28 |     ))}`enter code here`
  29 |   </div>

通常,map() 方法用於遍歷數組並在數組的每個元素上調用一個函數,如果我使用 userDataInfo 作為數組,那么為什么會出現此錯誤?

 const [userDataInfo, setUserDataInfo] = useState([]);

userDataInfo以數組開始


 .get("https://random-data-api.com/api/address/random_address")

但隨后您會得到返回對象(不是數組)的 JSON 表示形式的 URL。


 return JSON.stringify(response);

然后將對象轉換為 JSON 字符串,然后將該字符串存儲在setUserDataInfo中。


  • 不要將您的數據轉換為 JSON。 JSON 是一種可用於通過 API(如fetchlocalStorage )發送到外部位置的格式。 它對於內部處理數據結構沒有用。
  • 確定要存儲在userDataInfo中的數據格式。 如果您要在其中存儲多個地址,則使用一個數組(並更改您對來自 URL 的數據的處理以反映這一點……例如,通過添加到現有數組而不是用單個值覆蓋)。 如果您打算只使用一個項目,那么只存儲一個項目(並擺脫map )。

響應對象將采用以下格式

{
data:"some data"
}

假設 api 請求返回一個數組,那么您需要做的就是:

axios
      .get("https://random-data-api.com/api/address/random_address")
      .then(function (response) {
        setUserDataInfo(response.data);
      })

如果需要進一步澄清下面的響應模式,也許可以查看 axios 文檔:

https://axios-http.com/docs/res_schema

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM