未捕获的类型错误:无法读取未定义的属性“地图”-React js

时间:2021-01-07 04:41:04

标签: javascript reactjs react-hooks

我正在尝试通过传递索引来使用 setState({index: index }) 设置新状态,但出现以下错误

“未捕获的类型错误:无法读取未定义的属性‘地图’” 我正在使用 react hooks 并且我正在使用箭头函数,我真的不明白发生了什么......

enter image description here

有关如何解决此问题的任何建议?

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;

2 个答案:

答案 0 :(得分:2)

当您 setState({ index: index }) 时,它会删除您状态中的 products 属性。 那就去做吧

setState({ products, index: index })

答案 1 :(得分:1)

原因是您的产品状态在 handleTap 函数中被索引状态替换。如果不包含当前状态,useState 将用新状态替换当前状态。

如果将产品状态和索引状态分开会更好。例如:

const [products, setProducts] = useState([
  {
    _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",
    ],
 
  },
])
const [index, setIndex]= useState(0);

然后在你的 handleTab 函数中调用 setIndex 来更新索引