由于props不适用于v6,我应该做些什么才能使此代码适用于v6。如何传递正确的信息,以便按预期显示信息。
restaurant.js 中的片段
const Restaurant = props => {
const initialRestaurantState = {
id: null,
name: "",
address: {},
cuisine: "",
reviews: []
};
const [restaurant, setRestaurant] = useState(initialRestaurantState);
const getRestaurant = id => {
RestaurantDataService.get(id)
.then(response => {
setRestaurant(response.data);
console.log(response.data);
})
.catch(e => {
console.log(e);
});
};
useEffect(() => {
getRestaurant(props.match.params.id);
}, [props.match.params.id]);
App.js 中的代码段
<Route path="/restaurants/:id"render={(props) => (
<Restaurant {...props} user={user} />)}/>
您可以使用useParams
...
import { useParams } from 'react-router-dom';
...
...
const params = useParams();
useEffect(() => {
getRestaurant(params.id);
}, [params.id]);
...
这是参考资料https://reactrouter.com/docs/en/v6/api#useparams
您需要更改代码的某些部分:首先,使用useParams
而不是props.match.params.id
:
const params = useParams();
useEffect(() => {
getRestaurant(params.id);
}, [params.id]);
其次,Route
组件上没有任何render
道具,应该使用element
而不是render
:
<Route path="/restaurants/:id" element={(props) => (
<Restaurant {...props} user={user} />)}/>