简体   繁体   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 the console, it is displayed correctly, but it returns an empty array in the state 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",
      },
  ]
}

this is my useEffect:这是我的使用效果:

  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();
  }, []);

You can display it like this, and it will store the data in your useState() .您可以像这样显示它,它会将数据存储在您的useState()中。 I've created that formattedData to recreate your object我已经创建了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.

相关问题 为什么我不能在 React 中使用 useState 附加一个孩子? - Why can't I append a child using useState in React? React Context api,我无法从上下文获取对象 - React Context api, I can't get to object from context "如何在反应中使用 useState 更改幻灯片?" - How can I change slides with useState in react? 当api在react js中使用axios成功时,我可以使用多个useState并设置数据吗? - Can I use multiples useState and set data when api's got success using axios in react js? 为什么 useState 设置在 useEffect 中不起作用?我该如何解决这个问题? - Why useState set don't work inside useEffect in react?How can i fix this? 为什么我不能使用 useState() 在 React Native 的 panHandler 中创建计数器? - Why I can't create a counter within a panHandler in React Native with useState()? 用 useState 钩子更新对象的 state 后做出反应,我不能调用它的任何函数 - React after updating an object's state with useState hook, I can't call any of its functions 我无法定义类型以在变量 React.useState 中设置对象数组 - I can't define type to set an array of objects in a variable React.useState React从localStorage获取对象,无法使用react useState设置它 - React getting an object from localStorage, can't set it with react useState React - 如何在 useState 中从后端 API 获取初始值? - React - How get initial value from Backend API in useState?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM