React 路由器不呈现默认路由
React router not rendering default route
我正在尝试添加一个默认页面,用户在打开网站时首先访问该页面,但它没有呈现默认路由。我怎样才能解决这个问题?
反应路由器v6
注意:没有路由器也能正常工作,所以不应该是组件问题
import React, {useState} from 'react';
import './App.css';
import {BrowserRouter as Router, Routes, Route, Switch} from 'react-router-dom';
import AddNote from './components/noteDisplay/addNote/newNote.js'
import NoteDisplay from './components/noteDisplay/noteDisplay.js'
import secondPage from './components/secondPage/secondContainer.js'
const App = () => {
return (
<div className="App">
<h1 className="app-title">My notes</h1>
<Router>
<div>
<Routes>
<Route path='/second' component={secondPage}/>
<Route path='*' component={NoteDisplay}/>
</Routes>
</div>
</Router>
</div>
);
}
export default App;
react-router-dom
v6 Route
组件 API 与 v5 相比发生了重大变化。 component
道具和 render
和 children
函数道具已经一去不复返了,取而代之的是带有 ReactElement
、a.k.a 的单个 element
道具。 JSX.
declare function Route(
props: RouteProps
): React.ReactElement | null;
interface RouteProps {
caseSensitive?: boolean;
children?: React.ReactNode;
element?: React.ReactElement | null;
index?: boolean;
path?: string;
}
从旧的 Route
component
属性切换到 element
属性,并将路由组件作为 JSX 而不是对组件的引用传递。
<Routes>
<Route path='/second' element={<SecondPage />} />
<Route path='*' element={<NoteDisplay />} />
</Routes>
用户首先看到的页面是首页,用“/”指定。要使其成为默认值,您可以使用 Route 组件的 index 属性,如下所示
<Route path="/" element={<App />}>
<Route index element={<Home />} />
<Route path='/second' component={secondPage}/>
<Route path='*' component={NoteDisplay}/>
</Route>
我正在尝试添加一个默认页面,用户在打开网站时首先访问该页面,但它没有呈现默认路由。我怎样才能解决这个问题? 反应路由器v6 注意:没有路由器也能正常工作,所以不应该是组件问题
import React, {useState} from 'react';
import './App.css';
import {BrowserRouter as Router, Routes, Route, Switch} from 'react-router-dom';
import AddNote from './components/noteDisplay/addNote/newNote.js'
import NoteDisplay from './components/noteDisplay/noteDisplay.js'
import secondPage from './components/secondPage/secondContainer.js'
const App = () => {
return (
<div className="App">
<h1 className="app-title">My notes</h1>
<Router>
<div>
<Routes>
<Route path='/second' component={secondPage}/>
<Route path='*' component={NoteDisplay}/>
</Routes>
</div>
</Router>
</div>
);
}
export default App;
react-router-dom
v6 Route
组件 API 与 v5 相比发生了重大变化。 component
道具和 render
和 children
函数道具已经一去不复返了,取而代之的是带有 ReactElement
、a.k.a 的单个 element
道具。 JSX.
declare function Route( props: RouteProps ): React.ReactElement | null; interface RouteProps { caseSensitive?: boolean; children?: React.ReactNode; element?: React.ReactElement | null; index?: boolean; path?: string; }
从旧的 Route
component
属性切换到 element
属性,并将路由组件作为 JSX 而不是对组件的引用传递。
<Routes>
<Route path='/second' element={<SecondPage />} />
<Route path='*' element={<NoteDisplay />} />
</Routes>
用户首先看到的页面是首页,用“/”指定。要使其成为默认值,您可以使用 Route 组件的 index 属性,如下所示
<Route path="/" element={<App />}>
<Route index element={<Home />} />
<Route path='/second' component={secondPage}/>
<Route path='*' component={NoteDisplay}/>
</Route>