未捕获类型错误:无法读取未定义的属性(读取“img”)

问题描述 投票:0回答:4

ProductDetail.js 文件

import React from 'react'
import { useParams } from 'react-router-dom'
import DATA from '../Data';

const ProductDetail = () => {
  {/*Now we need a product id which is pass from the product page*/}
  const proid=useParams();
  const proDetail=DATA.filter(x=>x.id===proid.id)
  const product=proDetail[0]
  console.log(product)

  return (
    <>
      <div className='container my-5 py-3'>
        <div className='row'>
          <div className='col-md-6'>
            <img src={product.img} alt={product.title} />
          </div>
          <div className="col-md-6">
            <h1>{product.title}</h1>
            <hr />
            <h2>{product.price}</h2>
            <p>{product.desc}</p>
            <button className='btn btn-outline-primary'>Add to cart</button>
          </div>
        </div>
      </div>
    </>
  )
}

export default ProductDetail

App.js 文件

import './App.css';
import Header from './components/Header';
import {BrowserRouter, Routes,Route} from 'react-router-dom'
import Home from './components/Home';
import Product from './components/Product';
import About from './components/About';
import Contact from './components/Contact';
import Footer from './components/Footer';
import ProductDetail from './components/ProductDetail';


function App() {
  return (
    <div>
      <BrowserRouter>
        <Header/>
        <Routes>
          <Route path='/' element={<Home/>}/>
          <Route path='/product' element={<Product/>}/>
          <Route path='/product/:id' element={<ProductDetail/>}/>
          <Route path='/about' element={<About/>}/>
          <Route path='/contact' element={<Contact/>}/>
        </Routes>
        <Footer/>
      </BrowserRouter>
    </div>
  );
}

export default App;

Data.js 文件

const DATA=[
    {
        id: 0,
        title: 'Apple iPhone 11',
        price: 49900,
        desc: '6.1-inch (15.4 cm diagonal) Liquid Retina HD LCD display Water and dust resistant (2 meters for up to 30 minutes, IP68) Dual-camera system with 12MP Ultra Wide and Wide cameras; Night mode, Portrait mode, and 4K video up to 60fps 12MP TrueDepth front camera with Portrait mode, 4K video, and Slo-Mo Face ID for secure authentication A13 Bionic chip with third-generation Neural Engine Fast-charge capable',
        img: '/iphone1.jpg'
    },
    {
        id: 1,
        title: 'Apple iPhone 12 (128GB) - Blue',
        price: 58999,
        desc: '6.1-inch (15.5 cm diagonal) Super Retina XDR display Ceramic Shield, tougher than any smartphone glass A14 Bionic chip, the fastest chip ever in a smartphoneAdvanced dual-camera system with 12MP Ultra Wide and Wide cameras; Night mode, Deep Fusion, Smart HDR 3, 4K Dolby Vision HDR recording 12MP TrueDepth front camera with Night mode, 4K Dolby Vision HDR recording.Industry-leading IP68 water resistance.Supports MagSafe accessories for easy attach and faster wireless charging.iOS with redesigned widgets on the Home screen, all-new App Library, App Clips and more',
        img: '/blueapple.jpg'
    },
    {
        id: 2,
        title: 'Apple iPhone 11 (64GB) - (Product) RED',
        price: 47999,
        desc: '6.1-inch (15.4 cm diagonal) Liquid Retina HD LCD display Water and dust resistant (2 meters for up to 30 minutes, IP68).Dual-camera system with 12MP Ultra Wide and Wide cameras; Night mode, Portrait mode, and 4K video up to 60fps. 12MP TrueDepth front camera with Portrait mode, 4K video, and Slo-Mo Face ID for secure authentication.A13 Bionic chip with third-generation Neural EngineFast-charge capable',
        img: '/red.jpg'
    }
]

export default DATA
reactjs react-router-dom
4个回答
1
投票

您还可以使用可选链来检查现有属性。

https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Operators/Optional_chaining

{<img src={product?.img} alt={product.title} />}

1
投票

问题

path='/product/:id'
id
路径参数将是组件中的 String 类型。

const { id } = useParams(); // <-- id is a String

id
中的
DATA
属性是 Number 类型。

const DATA = [
  {
    id: 0, // <-- id is a Number
    ...
  },
  {
    id: 1, // <-- id is a Number
    ...
  },
  {
    id: 2, // <-- id is a Number
    ...
  }
]

这种类型不匹配会导致严格的

===
相等性检查在
ProductDetail
组件中失败。

const proid = useParams();
const proDetail = DATA.filter(x => x.id === proid.id); // returns empty array
const product = proDetail[0]: // undefined
console.log(product);

首次尝试访问未定义的属性 X 时会抛出错误。

<img
  src={product.img} // <-- first access throws error!!
  alt={product.title}
/>

解决方案

要使用严格的

===
相等性,请确保您使用的是类型安全的比较。您应该将所有值转换为字符串。您还应该妥善处理数据中未找到产品的情况。

示例:

const ProductDetail = () => {
  const { id } = useParams();
  const product = DATA.find(x => String(x.id) === id);
  console.log(product);

  return (
    <div className='container my-5 py-3'>
      <div className='row'>
        {product
          ? (
            <>
              <div className='col-md-6'>
                <img src={product.img} alt={product.title} />
              </div>
              <div className="col-md-6">
                <h1>{product.title}</h1>
                <hr />
                <h2>{product.price}</h2>
                <p>{product.desc}</p>
                <button className='btn btn-outline-primary'>
                  Add to cart
                </button>
              </div>
            </>
          )
          : (
            <div className='col-md-12'>
              No product matched
            </div>
          )
        }
      </div>
    </div>
  );
};

0
投票

您可能需要使用对象解构:

const {proid} = useParams();

0
投票

让同学们=[ { 编号:1, 广告:“埃利亚尔”, 索亚德:“艾哈迈德利”, 爱好:“idman”, 气数:80 }, { 编号:2, 广告:"Xeyale", 索亚德:"穆斯塔法耶娃", 爱好:“kitab oxumaq”, 气数:100 }, { 编号:3, 广告:“阿祖”, 索亚德:"穆萨耶娃", 爱好:“mahni oxumaq”, 气数:91 } , { 编号:4, 广告:“伊莱”, 索亚德:“埃利耶夫”, 爱好:“idman”, 气数:60 } ]; // console.log(学生); console.log((学生[0].qiymet + 学生[1].qiymet +学生[2].qiymet+学生[3].qiymet)/4); 对于 ( 让 i = 0 ; i <= students.length; i++){ if( students[i].qiymet <= 90){

  }

}

app.js:68未捕获的类型错误:无法读取未定义的属性(读取“qiymet”)

© www.soinside.com 2019 - 2024. All rights reserved.