开发者问题收集

React useEffect 无法读取未定义的属性“map”

2020-08-20
911
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>
  );
}
1个回答

几乎没有变化,你必须返回一个承诺。

示例代码:

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

const getNotes = () => {
  return new Promise (
    (resolve, reject) => 
   fetch('https://jsonplaceholder.typicode.com/todos')
   .then(data => resolve(data.json()))
   .catch(err => reject(err))
   )  
}

const ToDos = () => {
  const [toDos, setToDos] = useState([]);
  
  useEffect(() => {
    getNotes().then( data => setToDos(data))
  }, []);

  const renderData = () => toDos.map((toDo) => <li>title: { toDo.title } </li>)
  return (
    <Fragment>
      <ul>
      {renderData()}
      </ul>
    </Fragment>
  )
}

export default ToDos;

在你的情况下,完成 API 调用后,函数 getNotes 没有返回任何内容,因此 test 未定义,结果它分解为错误: 无法读取未定义的属性“map”

工作代码片段: https://codesandbox.io/s/react-playground-forked-bwt89?file=/ToDoSample.jsx

pankaj kumar
2020-08-21