簡體   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