【问题标题】: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我可以看到来自 python django 的 http get 请求中的对象数组,但是当它进入 jsx react 时,数据被转换为未定义
【发布时间】:2022-01-10 16:27:33
【问题描述】:

伙计们,我在 Django REST 框架中编写了一个小 API,它运行良好,我正在用 react js 编写它的前端,但问题是当我执行获取请求时,我可以看到值(数组对象)当我从 js 中的 API 帮助文件和调用帮助文件但数据不可访问或转换为未定义的函数进行控制台时,我正在下面编写代码

#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");
  }
}

以及我发出 get 请求的函数

// 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;
  }
}

谁能看到这个并告诉我我哪里做错了,我试图在互联网上找到完全不相关或不相关或我无法理解的东西...... 而且我认为它不会重复其他问题

【问题讨论】:

  • getAllTodos()async 但您在 useEffect() 调用它时将其视为同步

标签: javascript python reactjs api async-await


【解决方案1】:

我在你的课程中做了一些改动,虽然代码不一样,但它可以帮助你。

基本上是 getAllTodos() 异步函数,但您没有使用 await,这就是您看不到值的原因。

不要在 useEffect 中使用异步,在另一个函数中调用你的请求,然后在 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;

【讨论】:

    猜你喜欢
    • 2013-03-02
    • 2017-11-26
    • 1970-01-01
    • 2016-05-14
    • 2017-10-15
    • 1970-01-01
    • 1970-01-01
    • 2021-01-09
    相关资源
    最近更新 更多