繁体   English   中英

反应useEffect无法读取未定义的属性'map'

[英]React useEffect Cannot read property 'map' of undefined

 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 页面导入 function 并在 useEffect 中运行它。 function 应该击中我的后端,该后端从 mongo Atlas 检索数据并将其发送到我的前端进行映射。 数据是一个由 4 个对象组成的数组。 我无法 map 它,因为当组件呈现测试变量时未定义。 很长时间以来,我一直在努力理解这一点。 这将是一个巨大的帮助,请以一种不太技术化的方式解释我很难理解非常技术性的术语。 谢谢!

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

几乎没有变化,您必须返回 promise。

示例代码:

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 调用后,function getNotes没有返回任何内容,因此test未定义,因此它分解为错误: Cannot read property 'map' of undefined

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM