Я изучаю приложение для реагирования и пытаюсь использовать react-router-dom. Я набрал «http://localhost:3000/» в браузере. Я ожидаю, что «Дом» отображается в браузере. Однако, когда браузер отображает этот код, ничего не отображается.
import React from 'react';
import './App.css';
import { BrowserRouter, Route, Routes } from 'react-router-dom';
function App() {
return (
<>
<div>
<BrowserRouter>
<Routes>
<Route exact path='/' component = {HomePage} />
<Route path='/Contact' component = {ContactPage} />
<Route path='/About' component = {AboutPage} />
<Route component = {NotFoundPage} />
</Routes>
</BrowserRouter>
</div>
</>
);
}
function HomePage() {
return <h2>Home</h2>
}
function ContactPage() {
return <h2>Contact</h2>
}
function AboutPage() {
return <h2>About</h2>
}
function NotFoundPage() {
return <h2>NotFoundPage</h2>
}
export default App;
Я понятия не имею, почему это не работает правильно.
Если вы используете маршрутизатор v6, вам нужно использовать реквизит element
вместо component
. Но что более важно, вам нужно создать экземпляр компонента (изменить element = {HomePage}
на element = {< HomePage />}
).
См. документы: https://reactrouter.com/docs/en/v6/getting-started/concepts#defining-routes
import React from "react";
import { BrowserRouter, Route, Routes } from "react-router-dom";
function App() {
return (
<>
<div>
<BrowserRouter>
<Routes>
<Route exact path = "/" element = {<HomePage />} />
<Route path = "/Contact" element = {<ContactPage />} />
<Route path = "/About" element = {<AboutPage />} />
<Route component = {<NotFoundPage />} />
</Routes>
</BrowserRouter>
</div>
</>
);
}
function HomePage() {
return <h2>Home</h2>;
}
function ContactPage() {
return <h2>Contact</h2>;
}
function AboutPage() {
return <h2>About</h2>;
}
function NotFoundPage() {
return <h2>NotFoundPage</h2>;
}
export default App;