我目前正在开发一个 React 应用程序,我使用 React Router 进行导航。但是,我面临一个问题,即与路线关联的组件无法正确渲染。
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from '../components/App';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
document.addEventListener('DOMContentLoaded', () => {
const rootElement = document.getElementById('root');
if (rootElement) {
ReactDOM.render(
<Router>
<Routes>
<Route path="/" element={<App />} />
</Routes>
</Router>,
rootElement
);
document.body.appendChild(document.createElement('div'));
}
});
App.js
import React from "react"
import {Route, Routes, } from "react-router-dom"
import Gyms from "./Gyms/Gyms"
import Gym from "./Gym/Gym"
const App = () => {
return (
<Routes>
<Route path="/" component={Gyms}/>
<Route path="/gyms/:slug" component={Gym}/>
</Routes>
)
}
export default App;
Gym.js
import React from 'react'
const Gym = () => {
return <div>This is the Gym#show view for our app.</div>
}
export default Gym
Gyms.js
import React from 'react'
const Gyms = () => {
return <div>This is the Gyms#index view for our app.</div>
}
export default Gyms
尽管按上述方式设置了路线,但当我导航到路线时,我没有看到预期的组件渲染。相反,我只看到一个空白页。
在 React Router v6 中,指定路由组件的方式发生了变化。现在,您不再使用
component
属性,而是使用 element
属性并将组件作为 JSX 传递。
以下是如何调整 App.js 以符合 React Router v6 约定:
import React from "react";
import {Routes, Route } from "react-router-dom";
import Gyms from "./Gyms/Gyms";
import Gym from "./Gym/Gym";
const App = () => {
return (
<Routes>
<Route path="/" element={<Gyms/>}/>
<Route path="/gyms/:slug" element={<Gym/>}/>
</Routes>
);
}
export default App;