Reaction-TypeError:无法读取未定义的属性(正在读取参数) [英] React - TypeError: Cannot read properties of undefined (reading 'params')
本文介绍了Reaction-TypeError:无法读取未定义的属性(正在读取参数)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
因此我收到一条错误消息-TypeError:无法读取未定义的属性(正在读取‘Params’)
TypeError: Cannot read properties of undefined (reading 'params')
5 | import products from '../products'
6 |
7 | function ProductScreen({ match }) {
8 | const product = products.find((p) => p._id == match.params.id)
9 | return (
10 | <div>
11 | {product.name}
这是我的ProductScreen.js文件,其中出现问题
import React from 'react'
import { Link } from 'react-router-dom'
import { Row, Col, Image, ListGroup, Button, Card } from 'react-bootstrap'
import Rating from '../components/Rating'
import products from '../products'
function ProductScreen({ match }) {
const product = products.find((p) => p._id == match.params.id)
return (
<div>
{product.name}
</div>
)
}
export default ProductScreen
和我的App.js
import { Container } from 'react-bootstrap'
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom'
import Header from './components/Header'
import Footer from './components/Footer'
import HomeScreen from './screens/HomeScreen'
import ProductScreen from './screens/ProductScreen'
function 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;
我还尝试将match.params.id更改为Number或ParseInt(match.pars),但仍出现错误...
我知道这很简单,但我被困在这里,不能再往前走了。如有任何帮助,我们将不胜感激!
本教程中的另一个问题--在App.js中使用的是Components={}属性,而不是Element={}。当我尝试同样的方法时,它给了我一个错误,所以我不得不用另一种方法来修复它。您知道它为什么会导致错误吗?本教程
<Route path='/' component={HomeScreen} exact />
我的解决办法--
<Route path='/' element={<HomeScreen/>} exact />
api
本教程似乎较旧,并且使用的是react-router-dom
版本5,而您使用的是版本6。在版本6中有许多突破性的推荐答案更改。Route
组件不再使用component
或render
道具,传递有效JSX文本的element
道具取代了它们。route props(history
、location
和match
)也不再存在,路由组件必须现在使用Reaction挂钩来访问它们。
interface RouteProps { caseSensitive?: boolean; children?: React.ReactNode; element?: React.ReactElement | null; index?: boolean; path?: string; }
给定的路由:<Route path='/product/:id' element={<ProductScreen/>} />
useParams
挂钩访问id
匹配参数。匹配参数将是一个字符串,因此如果您的产品ID是数字类型,则为了确保严格相等,请将id
参数转换为数字:
import { Link, useParams } from 'react-router-dom';
...
function ProductScreen() {
const { id } = useParams();
const product = products.find((p) => p._id === Number(id));
return (
<div>
{product.name}
</div>
);
}
这篇关于Reaction-TypeError:无法读取未定义的属性(正在读取参数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文