我一直在尝试将组件动态路由到 url。使用了 userParam() 钩子。但它不是渲染。
数据在以下名为 servicesData.js 的文件中可用
let serviceData = [
{
"name": "Lawn Mowing",
"price": 30,
"_id": "1",
"description": "Have a carpet-like lawn without any work."
},
{
"name": "Leaf Raking",
"price": 50,
"_id": "2",
"description": "Remove those pesky dead tree parts from your property."
},
{
"name": "Weeding",
"price": 50,
"_id": "3",
"description": "Don't let the invaders ruin your yard."
},
{
"name": "Sprinkler repair",
"price": 100,
"_id": "4",
"description": "Keep your irrigation system top-notch."
}
]
export default serviceData
index.js 文件。
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
// import App from './App';
import reportWebVitals from './reportWebVitals';
import {BrowserRouter} from "react-router-dom"
import ServicesApp from "./ServicesApp.js"
ReactDOM.render(
<BrowserRouter>
<ServicesApp />
</BrowserRouter>,
document.getElementById('root')
);
reportWebVitals();
ServiceApp.js 文件。
import React from "react"
import Home from "./components/Home"
import ServicesList from "./pages/services/servicesList"
import ServiceDetail from "./pages/services/serviceDetail"
import HeaderService from "./components/HeaderService";
import {Switch, Route} from "react-router-dom"
function ServicesApp() {
return (
<div>
<HeaderService />
<Switch>
<Route exact path="/">
<Home />
</Route>
<Route exact path="/services" >
<ServicesList />
</Route>
<Route path="/services/:serviceId" >
<ServiceDetail />
</Route>
</Switch>
</div>
)
}
export default ServicesApp
servicesList.js 文件。
import React from "react"
import serviceData from "./servicesData"
import {Link} from "react-router-dom"
function ServicesList() {
const services = serviceData.map(service =>(
<h3 key={service._id}><Link to={`/services/${service._id}`}>{service.name}</Link> - ${service.price}</h3>
))
return(
<div>
<h1>Services List Page</h1>
{services}
</div>
)
}
export default ServicesList
ServiceDetail 文件是。
import React from "react"
import {useParams} from "react-router-dom"
import servicesData from "./servicesData"
function ServiceDetail(props) {
const {serviceId} = useParams()
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
const thisService = servicesData.find(service => service._id === serviceId)
return (
<div>
<h1>Service Detail Page</h1>
<h3>{thisService.name} - ${thisService.price}</h3>
<p>{thisService.description}</p>
</div>
)
}
export default ServiceDetail
HeaderService 文件。
import React from "react"
import {Link} from "react-router-dom"
function HeaderService() {
return (
<header>
<ul>
<li><Link exact to="/">Home</Link></li>
<li><Link exact to="/services">Services</Link></li>
</ul>
</header>
)
}
export default HeaderService