我确信我将要退出的教程已经过时了。我遇到了这个错误ProductDetails.js:27
Uncaught TypeError: Cannot read properties of undefined (reading 'params')
这是我的代码,其中ProductDetails.js:27
是分派、警报、错误,match.params.id:
import React, { Fragment, useEffect } from 'react'
import { Carousel } from 'react-bootstrap'
import Loader from '../layout/Loader'
import MetaData from '../layout/MetaData'
import { useAlert } from 'react-alert'
import { useDispatch, useSelector } from 'react-redux'
import { getProductDetails, clearErrors } from '../../actions/productActions'
const ProductDetails = ({ match }) => {
const dispatch = useDispatch();
const alert = useAlert();
const { loading, error, product } = useSelector(state => state.productDetails)
useEffect(() => {
dispatch(getProductDetails(match.params.id))
if(error) {
alert.error(error);
dispatch(clearErrors())
}
}, [dispatch, alert, error, match.params.id])
export default ProductDetails
不知道ProductDetails.js代码有多少,但它在这里,我省略了我的返回函数,因为它说我的帖子主要是代码。下面也是我的App.js代码:
import { BrowserRouter as Router, Route, Routes } from "react-router-dom"
import Header from './components/layout/Header'
import Footer from './components/layout/Footer'
import Home from './components/Home'
import ProductDetails from './components/product/ProductDetails'
function App() {
return (
<Router>
<div className="App">
<Header />
<div className="container container-fluid">
<Routes>
<Route path="/" element={<Home /> } exact />
<Route path="/product/:id" element={<ProductDetails /> } exact />
</Routes>
</div>
<Footer />
</div>
</Router>
);
}
export default App;
1条答案
按热度按时间icnyk63a1#
值得一提的是,
useParams
钩子自从React在react-router-dom@5
中引入钩子以来一直没有改变。问题是
match
只是未定义和/或未作为属性显式传递给此ProductDetails
组件。如果您使用const params = useParams()
和params
作为依赖项,则这很可能是渲染循环的原因,因为params
将是每个渲染循环的新对象引用。您应该直接引用id
参数。我还建议将效果拆分为两个单独的效果,这样
getProductDetails
就不会因为error
更新而被调度,反之亦然。示例: