match.params.id 显示白色空白全屏

match.params.id shows white blank full screen

我目前正在使用 MERN 开发电子商务网站。在 ProductScreen 中,我试图显示 Products.js 中列出的所有产品详细信息。在 ProductScreen.js 中添加 match.params.id 时显示空白页

ProductScreen.js:

import React from 'react'
import products from '../products'

const ProductScreen = ({ match }) => {
  const product = products.find(p => p._id === match.params.id)
  return (
    <div>{product.name}</div>
  )
}

export default ProductScreen

App.js:

import React from 'react'
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
import { Container } from 'react-bootstrap'
import Header from './components/Header'
import Footer from './components/Footer'
import HomeScreen from './screens/HomeScreen'
import ProductScreen from './screens/ProductScreen'

const App = () => {
  return (
    <Router>
      <Header />
      <main className='py-3'>
        <Container>
          <Routes>
            <Route path = '/' element={<HomeScreen />} exact />
            <Route path = '/product/:id' element={<ProductScreen />}  />
          </Routes>
        </Container>
      </main>
      <Footer />
    </Router>
  )
}

export default App

Product.js:

const products = [
  {
    _id: '1',
    name: 'Airpods Wireless Bluetooth Headphones',
    image: '/images/airpods.jpg',
    description:
      'Bluetooth technology lets you connect it with compatible devices wirelessly High-quality AAC audio offers immersive listening experience Built-in microphone allows you to take calls while working',
    brand: 'Apple',
    category: 'Electronics',
    price: 89.99,
    countInStock: 10,
    rating: 4.5,
    numReviews: 12,
  }
]

export default products

控制台日志错误: Error in console log

组件 ProductScreen 没有通过任何 match 属性。因此,当您尝试访问 params.id 时,它将抛出错误,因为无法读取未定义对象的属性。这可能就是您出现白屏崩溃的原因。

由于 ProductScreen 是一个功能组件,你可以使用 React Router hook 而不是通过 props 传递 matchuseRouteMatch()useParams().

const ProductScreen = () => {
  const params = useParams() // import useParams from react-router
  const product = products.find(p => p._id === params.id)
  return (
    <div>{product.name}</div>
  )
}

顺便说一句,当您出现空白屏幕时,请在浏览器中打开开发人员工具并阅读控制台中的错误消息。这将帮助您缩小问题的确切原因。