Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
462 views
in Technique[技术] by (71.8m points)

reactjs - TypeError: Cannot read property 'map' of undefined in react-hooks

I'm a beginner. Thank you in advance for sharing your knowledge.

This error did not appear originally.

But even though they used the same code, it is now appearing.

What's the reason?

Although the data received through Api has the form of an array, the 'map' method does not work.

I read the other same question but I couldn't solve this problem.

This error bothered me for a day. Let me know what I have to do.

import React, { useState, useEffect } from "react";
import axios from "axios";
import styled from "styled-components";

const MyModal = ({ onClose, selectedItem }) => {
  const [data, setData] = useState([]);
  let id = selectedItem;
  let url = `https://www.thecocktaildb.com/api/json/v1/1/lookup.php?i=${id}`;
  useEffect(() => {
    axios
      .get(url)
      .then((res) => {
        setData(res.data.drinks);
      })
      .catch((error) => {
        console.log(error);
      });
  }, [url]);
  return (
    <MyModals onClick={onClose}>
      <Wrapper>
        <button onClick={onClose}>X</button>
        {data.map((result) => { ?? This is the part of the problem.
          return (
            <Container>
              <Image>
                <img src={result.strDrinkThumb} alt={result.idDrink} />
              </Image>
              <About>
                <Name>{result.strDrink}</Name>
            </Container>
          );
        })}
      </Wrapper>
    </MyModals>
  );
};

export default MyModal;

Likewise, this file has the same problem. Errors appear and then appear.

import React, { useState, useEffect } from "react";
import styled from "styled-components";
import Portal from "../Components/Portal";
import Modal from "../Components/Modal";

const Search = () => {
  const [searchTerm, setSearchTerm] = useState("a");
  const [cocktails, setCocktails] = useState([]);
  const [open, setOpen] = useState(false);
  const [selectedItem, setSelectedItem] = useState("");

  const handleOpen = (idDrink) => {
    setSelectedItem(idDrink);
    setOpen(true);
    console.log("open");
  };

  const handleClose = () => {
    setOpen(false);
    console.log("close");
  };
  useEffect(() => {
    const getDrinks = async () => {
      try {
        const response = await fetch(
          `https://www.thecocktaildb.com/api/json/v1/1/search.php?s=${searchTerm}`
        );
        const data = await response.json();
        setCocktails(data);
      } catch (error) {
        console.log(error);
      }
    };
    getDrinks();
    console.log("useEffect");
  }, [searchTerm]);

  return (
    <main style={{ width: "100%" }}>
      <SearchForm setSearchTerm={setSearchTerm} />
      <Wrapper className="cocktail-list">
        {cocktails &&
          cocktails.drinks.map(({ idDrink, strDrink, strDrinkThumb }) => (
            <Container
              className="cocktail"
              onClick={() => {
                handleOpen(idDrink);
              }}
            >
              <Img>
                <img src={`${strDrinkThumb}`} alt={`${strDrink}`} />
              </Img>
              <Name key={`${idDrink}`}>{`${strDrink}`}</Name>
            </Container>
          ))}
      </Wrapper>
      {open && (
        <Portal>
          <Modal selectedItem={`${selectedItem}`} onClose={handleClose} />
        </Portal>
      )}
    </main>
  );
};

export default Search;

Is there a problem with the part where I receive the Api data?

import React from "react";
import styled from "styled-components";
import { useState, useEffect } from "react";
import Search from "./Search";
import Modal from "../Components/Modal";
import Portal from "../Components/Portal";

const Main = () => {
  const url = "https://www.thecocktaildb.com/api/json/v1/1/random.php";
  const [data, setData] = useState([]);
  const [open, setOpen] = useState(false);
  const [selectedItem, setSelectedItem] = useState("");

  useEffect(() => {
    const fetchUrl = async () => {
      try {
        const response = await fetch(url);
        const json = await response.json();
        setData(json);
      } catch (error) {
        console.log(error);
      }
    };
    console.log("useEffect");
    fetchUrl();
  }, []);

  const handleOpen = (idDrink) => {
    setSelectedItem(idDrink);
    setOpen(true);
    console.log("open");
  };
  const handleClose = () => {
    setOpen(false);
    console.log("close");
  };

  return (
    <Wrapper className="main">
      {data &&
        data.drinks.map(({ idDrink, strDrink, strDrinkThumb }) => (
          <>
            <Container
              onClick={() => {
                handleOpen(idDrink);
                console.log(handleOpen(idDrink));
              }}
            >
              <img src={`${strDrinkThumb}`} alt={`${strDrink}`} />
              <div key={`${idDrink}`}>{`${strDrink}`}</div>
            </Container>
            {open && (
              <Portal>
                <Modal selectedItem={`${selectedItem}`} onClose={handleClose} />
              </Portal>
            )}
          </>
        ))}
      <Search />
    </Wrapper>
  );
};
export default Main;

The error occurred in all files that wrote the 'map' method.

I really don't know what the problem is. Help me!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This has occurred because your map() called before the data come from API. So I will suggest first complete the API call and let the data came properly. Then you should map. You can use-

{data && data.map((result) => { ?? This will solve ur problem
      return (
        <Container>
          <Image>
            <img src={result.strDrinkThumb} alt={result.idDrink} />
          </Image>
          <About>
            <Name>{result.strDrink}</Name>
        </Container>
      );
    })}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...