无法读取未定义的属性(读取“map”)

3

我需要你的帮助。我正在尝试通过redux获取API数据。我已经拥有了所需的一切:action_types、action_creators、reducer。但是当我尝试提取数据时,出现错误:Cannot read properties of undefined (reading 'map')。请问我的错误在哪里?非常感谢你的帮助。下面是我的代码:

cartoons.js

import React, {useEffect} from "react";
import {useDispatch, useSelector} from "react-redux";
import {cartoons_are_loaded} from "../redux/action_creators";

export let Cartoons = () => {

let dispatch = useDispatch();
let cartoons = useSelector(({cartoon_reducer: {cartoons}}) => cartoons);

let fetchCartoons = async () => {
    try {
        let response = await fetch('https://api.sampleapis.com/cartoons/cartoons2D');
        let json = await response.json();
        console.log(json);
        dispatch(cartoons_are_loaded(json.data))
    } catch (e) {
        console.log(e)
    }
}

useEffect(() => {
   if (!cartoons.length){
       fetchCartoons();
   }
},[])

return (<div>
    {cartoons.map(el => <div key={el.id}>{el.title}</div>)}
        </div>)
}

reducers.js

import {CARTOONS_ARE_LOADED} from "./action_types";

let initialState = {
cartoons: []
}

let cartoon_reducer = (state = initialState, action) => {
switch (action.type) {
    case CARTOONS_ARE_LOADED: {
        return {
            ...state,
            cartoons: action.payload
        }
    }

    default:
        return state;
}
}
export default cartoon_reducer;

action_types.js

let CARTOONS_ARE_LOADED = 'CARTOONS_ARE_LOADED';
let DELETE_FAVOURITE_MOVIE = 'DELETE_FAVOURITE_MOVIE';
let ADD_FAVOURITE_CARTOON = 'ADD_FAVOURITE_MOVIE';
export {
CARTOONS_ARE_LOADED,
ADD_FAVOURITE_CARTOON,
DELETE_FAVOURITE_MOVIE
}

action_creators.js

import {
CARTOONS_ARE_LOADED,
} from "./action_types";
let cartoons_are_loaded = (payload) => ({type : CARTOONS_ARE_LOADED, payload});
export {
cartoons_are_loaded
}

all_reducers.js

import cartoon_reducer from "./reducers";
import {combineReducers} from "redux";
export let root_reducer = combineReducers({
cartoon_reducer
})

对于 CARTOONS_ARE_LOADED 这种情况,action.payload 的值是什么?看起来你没有维护数组的状态不变性。 - Drew Reese
我建议使用浏览器开发者工具来调试你的代码。你应该安装React Dev工具和Redux Dev工具。 - Code-Apprentice
@Code-Apprentice,好的我会安装。我还有一个问题,我发送了10次这样的请求。但是我尝试绘制9个组件时,数据没有绘制出来,尽管我完全按照同一个示例操作。请问查询执行是否有任何限制? - Dmitry Chernyak
@Ronald 你应该点击页面右上角的按钮发布一个新问题。 - Code-Apprentice
1个回答

1

问题

JSON响应已经是一个数组。

let json = await response.json();
// 20210915235745
// https://api.sampleapis.com/cartoons/cartoons2D

[
  {
    "title": "Spongebob Squarepants",
    "year": 1999,
    "creator": [
      "Stephen Hillenburg"
    ],
    "rating": "TV-Y",
    "genre": [
      "Comedy",
      "Family"
    ],
    "runtime_in_minutes": 23,
    "episodes": 272,
    "image": "https://nick.mtvnimages.com/uri/mgid:arc:content:nick.com:9cd2df6e-63c7-43da-8bde-8d77af9169c7?quality=0.7",
    "id": 1
  },
  ...
  {
    "title": "The New Adventures of Winnie the Pooh",
    "year": 1988,
    "creator": [
      "Karl Geurs",
      "Terence Harrison",
      "Ken Kessel"
    ],
    "rating": "TV-Y",
    "genre": [
      "Adventure",
      "Comedy"
    ],
    "runtime_in_minutes": 30,
    "episodes": 50,
    "image": "https://m.media-amazon.com/images/M/MV5BZjFkZDkwYjktMmZkNi00ZTVkLWI5ZmItZWI2MmI1NjQ1Y2U0XkEyXkFqcGdeQXVyOTg4MDk3MTQ@._V1_SY1000_CR0,0,666,1000_AL_.jpg",
    "id": 23
  }
]

没有 data 属性,换句话说,json.data 未定义,因此无法进行映射。

解决方案

只需使用 json 的 JSON 数据值调度操作即可:

dispatch(cartoons_are_loaded(json))

完整代码:

const fetchCartoons = async () => {
  try {
    let response = await fetch('https://api.sampleapis.com/cartoons/cartoons2D');
    let json = await response.json();
    console.log(json);
    dispatch(cartoons_are_loaded(json)) // <-- pass just `json`
  } catch (e) {
    console.log(e)
  }
}

这是一个使用本地状态替代redux的示例codesandbox:

Edit cannot-read-properties-of-undefined-reading-map


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接