[英]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>
Generally, the map() method is used to iterate over an array and call a function on every element of the array and if I am using userDataInfo as an array then why I am getting this error?通常,map() 方法用于遍历数组并在数组的每个元素上调用一个函数,如果我使用 userDataInfo 作为数组,那么为什么会出现此错误?
const [userDataInfo, setUserDataInfo] = useState([]);
userDataInfo
starts out as an array. userDataInfo
以数组开始。
.get("https://random-data-api.com/api/address/random_address")
But then you get that URL which returns a JSON representation of an object (not an array).但随后您会得到返回对象(不是数组)的 JSON 表示形式的 URL。
return JSON.stringify(response);
And then you convert the object into a string of JSON before storing that string in setUserDataInfo
.然后将对象转换为 JSON 字符串,然后将该字符串存储在
setUserDataInfo
中。
fetch
or localStorage
). fetch
或localStorage
)发送到外部位置的格式。 It isn't useful for processing data structures internally.userDataInfo
.userDataInfo
中的数据格式。 If you are going to store multiple addresses in there, then use an array (and change your handling of the data from the URL to reflect that … eg by adding to an existing array instead of overwriting with a single value).map
).map
)。response object would be in the following format响应对象将采用以下格式
{
data:"some data"
}
assuming that the api request returns an array then all you need to do is:假设 api 请求返回一个数组,那么您需要做的就是:
axios
.get("https://random-data-api.com/api/address/random_address")
.then(function (response) {
setUserDataInfo(response.data);
})
perhaps take a look at the axios documentation if need further clarification on the response schema below:如果需要进一步澄清下面的响应模式,也许可以查看 axios 文档:
https://axios-http.com/docs/res_schema https://axios-http.com/docs/res_schema
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.