簡體   English   中英

我可以看到進入我的 http 的對象數組從 python django 獲取請求,但是當它進入 jsx 反應時,數據被轉換為未定義

[英]i can see array of objects coming in my http get request from python django but data gets converted into undefined when it comes inside jsx react

guys, I have written a rest API a small one in Django rest framework and its working nicely and I am writing its front end in react js but the problem is when I do the get request I can see the values(array of objects) when我從 js 中的 API 輔助文件和調用輔助文件的 function 進行控制台,但數據無法訪問或轉換為未定義,我在下面編寫代碼

#my env
REACT_APP_API_URL = http://192.168.43.18:8000/api/
# I know its not needed but I am trying to talk more in context
// my jsx
import React, { useEffect, useState } from "react";
import { getAllTodos as getAllTodo } from "./apis/todo-helper";
import TodoSingle from "./parts/TodoSingle";

function HomeTodo() {
  const [todoList, setTodoList] = useState([]);
  useEffect(() => {
    try {
      const data = getAllTodo();
      setTodoList(data);
    } catch (error) {
      console.error(error);
    }
  }, []);

  return (
    <div>
      {console.log(typeof todoList, "typeof todoList")}
      {todoList.length > 0 &&
        todoList.map((item, index) => {
          console.log(item, index);
          return <TodoSingle todo={item} />;
        })}
    </div>
  );
}

export default HomeTodo;
// my helper function or just a function which calls the HTTP method
import { todoAPIs } from "./../../utils/ep";
import { get } from "../../utils/http";

export async function getAllTodos() {
  try {
    const data = await get(`${todoAPIs.home}`);
    console.log(data.json());
    return data;
  } catch (error) {
    console.log(error, "error in get All todos");
  }
}

和我的 function 我正在其中提出獲取請求

// http.js
const HTTP_METHOD = Object.freeze({
  GET: "GET",
  POST: "POST",
  PUT: "PUT",
  DELETE: "DELETE",
});

const BASE_URL = process.env.REACT_APP_API_URL;

function genericHeaders() {
  const headers = {
    "Content-Type": "application/json",
  };

  return headers;
}

export async function get(ep, include = false, headers = genericHeaders()) {
  return makeRequest(ep, HTTP_METHOD.GET, null, include, headers);
}

export async function post(
  ep,
  body,
  include = false,
  headers = genericHeaders()
) {
  return makeRequest(
    ep,
    HTTP_METHOD.POST,
    JSON.stringify(body),
    include,
    headers
  );
}

export async function put(
  ep,
  body,
  include = false,
  headers = genericHeaders()
) {
  return makeRequest(
    ep,
    HTTP_METHOD.PUT,
    JSON.stringify(body),
    include,
    headers
  );
}

export async function del(
  ep,
  body,
  include = false,
  headers = genericHeaders()
) {
  return makeRequest(
    ep,
    HTTP_METHOD.DELETE,
    JSON.stringify(body),
    include,
    headers
  );
}

async function makeRequest(ep, method, body, includeCredentials, headers) {
  const config = {
    method,
    headers,
  };
  // Set configurations.
  if (includeCredentials) config.credentials = "include";
  if (body) config.body = body;

  // console.log(token, 'token')

  try {
    const response = await fetch(BASE_URL + ep, config);
    const data = await response.json();
    console.info(data);
    return data;
    // return Object.assign([], data);
  } catch (error) {
    console.error(ep, body, error);
    throw error;
  }
}

誰能看到這個並告訴我我做錯了什么,我試圖在互聯網上找到完全不相關或不相關或我無法理解的東西......而且我認為它不會重復其他問題

我對您的 class 進行了一些更改,它的代碼不同,但它可以幫助您。

基本上 getAllTodos() async function 但你沒有使用 await 這就是為什么你看不到你的值。

不要在 useEffect 中使用異步,在另一個 function 中調用您的請求,然后在 useEffect 中調用它。

這是你的演示。

import React, { useEffect, useState } from 'react';

function HomeTodo() {
  const [todoList, setTodoList] = useState([]);

  const getAllTodos=async()=> {
    try {
      const data = await new Promise(resolve=> resolve([1, 2, 3]));
      return data;
    } catch (error) {
      console.log(error, 'error in get All todos');
    }
  };

  const loadData =async()=>{
    try {
      const data = await getAllTodos();
      setTodoList(data);
    } catch (error) {
      console.error(error);
    }
  };

  useEffect(() => {
    loadData();
  }, []);



  return (
    <div>
      {console.log(typeof todoList, 'typeof todoList')}
      {todoList.length > 0 &&
        todoList.map((item, index) => {
          console.log(item, index);
          return <div key ={index + item}todo={item}>{item}</div>;
        })}
    </div>
  );
}

export default HomeTodo;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM