繁体   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