× TypeError: Cannot read properties of null (reading 'map')

× TypeError: Cannot read properties of null (reading 'map')

我不明白为什么会出现此错误TypeError:无法读取 null 的属性(读取 'map'),这是一个非常简单的功能。我希望有人能帮助我。

这是我的代码,我无法映射来自 API 请求的对象。 为了隐私,我修改了API请求的key。

import { useEffect, useState } from "react";

export default function Featured() {

    const [featured, setFeatured] = useState(null);

    useEffect(() => {
        fetch('https://api.rawg.io/api/games?dates=2021-01-01,2021-12-31&ordering=-rating&key=1234')
        .then(response => response.json())
        .then(data => {
            console.log(data.results.slice(0, 4));
            setFeatured(data.results.slice(0, 4));
        });
    }, []);


    return (
        <div className="container mt-5">
            <div className="row">
                {featured.map((el) => {
                    return (
                        <div>{el.name}</div>
                    )
                })}
            </div>
        </div>
    );
}

您的问题是因为您的数据以 null 开始。在 api 有机会返回之前的初始渲染中,您的 featured 数组实际上是 null,您不能在 null 上调用 .map。相反,您可以像这样

将数据作为空数组开始

const [featured, setFeatured] = useState([]);

或者您可以检查您的渲染以确保它不再是 null api 返回响应后的情况。