我正在尝试从 url 中提取参数并使用 useParams 将其保存为 redux 变量。所以我想要的是以下内容:
我的问题是函数 this.props.setRestaurantId(id) 没有定义,我真的不知道为什么。您有什么建议吗?
这是我的代码:
import React from 'react';
import {BrowserRouter as Router, Switch, Route, Link, useRouteMatch, useParams} from "react-router-dom";
import HomeComponent from '../components/pages/home';
import AboutComponent from '../components/pages/about';
import RestaurantComponent from '../components/pages/restaurantProfile/restaurant';
import RestaurantList from "../components/pages/restaurantList";
import GetRestaurantId from "./getRestarauntID";
function router(){
return (
<Router>
<Switch>
<Route path="/about">
<About/>
</Route>
<Route path="/restaurant/:id" children={<GetRestaurantId/>}/>
<Route path="/restaurants">
<Restaurants/>
</Route>
<Route path="/impressum">
<Impressum/>
</Route>
<Route path="/">
<Home/>
</Route>
</Switch>
</Router>
);
}
function Home() {
return <HomeComponent/>
}
function About() {
return <AboutComponent/>;
}
function Restaurants(){
return <RestaurantList/>;
}
function Impressum(){
return <h2>Impressum</h2>
}
export default router;
import React from 'react';
import {BrowserRouter as Router, Switch, Route, Link, useRouteMatch, useParams} from "react-router-dom";
import {connect} from "react-redux";
import Restaurant from "../components/pages/restaurantProfile/restaurant";
function GetId() {
const { id } = useParams();
console.log(id);
this.props.setRestaurantId(id);
return(
<div>
<Restaurant/>
</div>
)
}
const mapDispatchToProps=(dispatch)=>{
return {
setRestaurantId: (data) => dispatch({type:'SET_RESTAURANT_ID', payload:data}),
}
};
export default connect(null,mapDispatchToProps)(GetId);
答案 0 :(得分:1)
您不能在功能组件中使用 this.props
。
您可以直接从函数参数中访问道具。
function GetId({setRestaurantId}) {
const { id } = useParams();
console.log(id);
setRestaurantId(id);
return(
<div>
<Restaurant/>
</div>
)
}
const mapDispatchToProps=(dispatch)=>{
return {
setRestaurantId: (data) => dispatch({type:'SET_RESTAURANT_ID', payload:data}),
}
};
export default connect(null,mapDispatchToProps)(GetId);