【问题标题】:How to solve Uncaught TypeError: Cannot read properties of undefined (reading 'map') in React如何解决 Uncaught TypeError: Cannot read properties of undefined (reading 'map') in React
【发布时间】:2022-06-23 00:18:53
【问题描述】:

我是 React 新手,使用 API 并努力解决此错误。我正在尝试使用 React.js 显示一系列图像并收到以下错误:

Popular.jsx:26 Uncaught TypeError: Cannot read properties of undefined (reading 'map')

在此错误下,我还收到以下错误:

上述错误发生在组件中:在Popular(http://localhost:3001/static/js/bundle.js:120:80) 在 div 在家 在 div 在页面 在 div 在应用程序 考虑向树中添加错误边界以自​​定义错误处理行为。 请访问https://reactjs.org/link/error-boundaries 了解有关错误边界的更多信息。

请告知我如何解决此错误。我已经尝试过 youtube 和 google,但似乎无法解决此错误。

我的代码:

import { useEffect, useState } from 'react';
import styled from 'styled-components';
import { Splide, SplideSlide } from '@splidejs/react-splide';
import '@splidejs/splide/dist/css/splide.min.css';

function Popular() {
  const [popular, setPopular] = useState([]);

  useEffect(() => {
    getPopular();
  }, []);
  console.log(process.env.REACT_APP_API_KEY);
  const getPopular = async () => {
    const api = await fetch(
      `https://api.spoonacular.com/recipes/random?apiKey=${process.env.REACT_APP_API_KEY}&number=9`
    );
    const data = await api.json();

    setPopular(data.recipes);
  };

  return (
    <div>
      <Wrapper>
        <h3>Popular Picks</h3>
        <Splide
          options={{
            perPage: 4,
            arrows: false,
            pagination: false,
            drag: 'free',
            gap: '5rem'
          }}
        >
          {popular.map((recipe) => {
            return (
              <SplideSlide>
                <Card>
                  <p>{recipe.title}</p>
                  <img src={recipe.image} alt={recipe.title} />
                </Card>
              </SplideSlide>
            );
          })}
        </Splide>
      </Wrapper>
    </div>
  );
}

const Wrapper = styled.div`
  margin: 4rem 0rem;
`;

const Card = styled.div`
min-height: 25rem;
border-radius: 2rem;
overFlow: hidden;
position: relative;

img{
border-radius: 2rem;
position: absoute;
left: 0;
width: 100%;
height: 100%;
object-fit: cover;
}

p{
  position: absolute;
  z-index: 10;
  left: 50%;
  bottom: 0%;
  transform: translate(-50%, 0%);
  color: white;
  width: 100%;
  text-align: center;
  font-weight: 600;
  font-size: 1rem;
  height: 40%;
  display: flex;
  justify-content: center;
  align-items: center;

}

`;

export default Popular;

提前致谢!

【问题讨论】:

    标签: css reactjs styled-components splidejs


    【解决方案1】:

    您正在使用空数组正确初始化您的状态,因此.map 不应引发错误。

    我怀疑您的 API 密钥/调用/响应有问题。尝试在此行之后记录响应:const data = await api.json();

    例如,如果我在没有密钥的情况下调用 API,我会收到以下响应:

      { 
        status: "failure", 
        code: 401, message: 
        "You are not authorized. Please read https://spoonacular.com/food-api/docs#Authentication" 
      }
    

    如果您遇到错误并致电setPopular(data.recipes);,您基本上是在说setPopular(undefined)。而undefined.map(...) 会抛出错误。

    一个包罗万象的解决方案是检查popular 是否为truthy

    在您的渲染方法中将{popular.map((recipe) =&gt; { 更改为 {popular &amp;&amp; popular.map((recipe) =&gt; {

    或者,如果您想确保没有错误,可以检查 popular 是否为数组:
    {Array.isArray(popular) &amp;&amp; popular.map((recipe) =&gt; {

    当没有数据时,你可以使用类似的东西来渲染不同的组件:

      if (popular) {
        <SplideSlide>...</SplideSlide>
      } else {
        <NoSlidesAvailableComponent />
      }
    

    【讨论】:

      猜你喜欢
      • 2021-11-10
      • 2021-12-31
      • 2023-01-23
      • 2022-10-18
      • 2022-01-11
      • 1970-01-01
      • 2022-10-09
      • 2022-07-21
      • 2022-07-22
      相关资源
      最近更新 更多