【问题标题】:React useEffect Cannot read property 'map' of undefined反应useEffect无法读取未定义的属性'map'
【发布时间】: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


【解决方案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 未定义,因此它分解为错误:Cannot read property 'map' of undefined

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

【讨论】:

    猜你喜欢
    • 2023-01-11
    • 1970-01-01
    • 2021-08-28
    • 2022-07-11
    • 2022-07-27
    • 1970-01-01
    • 1970-01-01
    • 2022-10-08
    • 1970-01-01
    相关资源
    最近更新 更多