【发布时间】:2020-08-20 16:49:14
【问题描述】:
import { handleResponse, handleError } from "./apiUtils";
const baseUrl = process.env.REACT_APP_API_URL;
export function getAllNotes() {
return fetch(baseUrl + "/notes", {
method: "GET",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
})
.then(res =>res.json())
.then(data=>console.log(data))
}
export async function handleResponse(response) {
if (response.ok) return response.json();
if (response.status === 400) {
// So, a server-side validation error occurred.
// Server side validation returns a string error message, so parse as text instead of json.
const error = await response.text();
throw new Error(error);
}
throw new Error("Network response was not ok.");
}
// In a real app, would likely call an error logging service.
export function handleError(error) {
// eslint-disable-next-line no-console
console.error("API call failed. " + error);
throw error;
}
我正在尝试学习 React 功能组件并熟悉 React Hooks。我正在从 Api.js 页面导入一个函数并在 useEffect 中运行它。该函数应该命中我的后端,该后端从 mongo Atlas 检索数据并将其发送到我的前端以进行映射。数据是一个由 4 个对象组成的数组。我无法映射它,因为当组件呈现测试变量时未定义。很长时间以来,我一直在努力理解这一点。这将是一个巨大的帮助,请以一种不太技术化的方式解释我很难理解非常技术性的术语。谢谢!
import React, {useState, useEffect} from 'react';
import {getAllNotes} from '../api/authorApi'
function CourseList(props) {
const [test, setTest] =useState([])
useEffect(()=>{
getAllNotes().then(_test=> setTest(_test))
}, []);
return (
<table className="table">
<thead>
<tr>
<th>Title</th>
<th>Author ID</th>
<th>Category</th>
</tr>
</thead>
<tbody>
{test.map(course => {
return (
<tr key={course.user_id}>hi
</tr>
);
})}
</tbody>
</table>
);
}
【问题讨论】:
-
问题在于
getAllNotes函数,而不是提供的代码(很可能) -
这段代码似乎没问题。 getAllNotes 里面可能有问题?
-
` 测试变量是未定义的` 最初的值是一个空数组,它不是未定义的,然后你用
_test设置它所以问题就在那里,_test不是你的期待 -
这是从另一个文件导入的函数:export function getAllNotes() { return fetch(baseUrl + "/notes", { method: "GET", headers: { 'Accept': 'application /json', 'Content-Type': 'application/json' } }) .then(res =>res.json()) .then(data=>console.log(data)) }
-
请使用附加代码更新您的问题。此外,您应该检查提取请求的
res.ok以确保提取成功。 developer.mozilla.org/en-US/docs/Web/API/Fetch_API/…
标签: javascript reactjs react-hooks es6-promise