[英]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
中。
fetch
或localStorage
)發送到外部位置的格式。 它對於內部處理數據結構沒有用。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 文檔:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.