Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - Uncaught TypeError: Cannot read property 'map' of undefined - React js

I'm trying to set the new state with setState({index: index }) by passing the index but I got the following error

"Uncaught TypeError: Cannot read property 'map' of undefined" I'm using react hooks and also I'm using an arrow function, I do not really understand what's going on...

enter image description here

Any suggestion on how to fix this issue?

import { useState } from "react";
import "./App.css";

const App = () => {
  const [state, setState] = useState({
    products: [
      {
        _id: "1",
        title: "Shoes",
        src: [
          "https://www.upsieutoc.com/images/2020/01/07/img2.png",
          "https://www.upsieutoc.com/images/2020/01/07/img2.png",
        ],
     
      },
    ],
    index: 0,
  });

  const { products, index } = state;
  console.log("index", index);

  const handleTab = (index) => {
    console.log("index", index);
    setState({ index: index });
  };

  return (
    <div className="App">
      {products.map((item) => (
       <div className="details" key={item._id}>
          <div >
            <img src={item.src[index]} alt="" />
          </div>

          <div>
        
            <div className="thumb">
              {item.src.map((img, indx) => (
                <img
                  src={img}
                  alt="img"
                  key={indx}
                  onClick={() => handleTab(indx)}
                />
              ))}
            </div>
          </div>
        </div>
      ))}
    </div>
  );
};

export default App;


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

1 Answer

0 votes
by (71.8m points)

When you setState({ index: index }) it remove the products property inside your state. Then do it instead

setState({ products, index: index })

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...