【发布时间】: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