繁体   English   中英

我无法在 React 中保存 UseState get api

[英]i can't save UseState get api in React

This is my output that I get from this GET url: https://localhost/get-all but I can't save this value in the useState: const [dataCat, setDataCat] = useState([]) When I display it in控制台,它显示正确,但它在 state 中返回一个空数组

{
  "categories": [
      {
          "id": 1,
          "name": "test1",
          "slug": "intelligence-and-memory-tests",
          "description": null,
      },
      {
          "id": 2,
          "name": "test2",
          "slug": "occupational-and-organizational-tests",
          "description": null,
      },
      {
          "id": 3,
          "name": "test3",
          "slug": "love-and-marriage-tests",
      },
  ]
}

这是我的使用效果:

  useEffect(() => {
    const fetchData = async () =>{
      try {
        const {data} = await axios.get('https://localhost/get-all');
        console.log(data);
        setDataCat(data)
      } catch (error) {
        console.error(error.message);
      }
    }
  
    fetchData();
  }, []);

您可以像这样显示它,它会将数据存储在您的useState()中。 我已经创建了formattedData来重新创建您的 object

import { useEffect, useState } from "react";
import axios from "axios";
import "./styles.css";

export default function App() {
  const [dataCat, setDataCat] = useState([]);
  const [newDataCat, setNewDataCat] = useState([]);
  // console.log("dataCat", dataCat);
  // console.log("newDataCat", newDataCat);

  const formattedData = (infoData) => {
    let newDataCat = [];
    infoData.forEach((item) =>
      newDataCat.push({
        id: item.id,
        name: item.name,
        slug: item.slug,
        description: item.description
      })
    );
    return newDataCat;
  };

  useEffect(() => {
    const fetchData = async () => {
      try {
        const { data } = await axios.get(
          "https://localhost/get-all"
        );
        setDataCat(data.categories);
      } catch (error) {
        console.error(error.message);
      }
    };

    fetchData();
  }, []);

  useEffect(() => {
    const cat = formattedData(dataCat);
    setNewDataCat(cat);
  }, [dataCat]);

  return (
    <>
      {newDataCat &&
        newDataCat.map((item) => {
          return (
            <>
              <h2>{item.id}</h2>
              <h2>{item.name}</h2>
              <h2>{item.slug}</h2>
            </>
          );
        })}
    </>
  );
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM