reactjs React路由器未呈现默认路由

ryhaxcpt  于 2022-12-29  发布在  React
关注(0)|答案(3)|浏览(207)

我尝试添加默认页面,用户打开网站时首先会转到该页面,但它无法呈现默认路由。我该如何解决此问题?react router 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;
c9x0cxw0

c9x0cxw01#

与v5相比,react-router-dom v6 Route组件API发生了重大变化。component属性、renderchildren函数属性消失了,取而代之的是一个element属性,该属性采用ReactElement,又名JSX。
路线和路线

declare function Route(
  props: RouteProps
): React.ReactElement | null;

interface RouteProps {
  caseSensitive?: boolean;
  children?: React.ReactNode;
  element?: React.ReactElement | null;
  index?: boolean;
  path?: string;
}

从旧的Routecomponent prop切换到element prop,并将路由的组件作为JSX而不是对该组件的引用传递。

<Routes>
  <Route path='/second' element={<SecondPage />} />
  <Route path='*' element={<NoteDisplay />} />
</Routes>

lb3vh1jj

lb3vh1jj2#

用户首先看到的页面是主页,用“/"指定。要将其设为默认值,可以使用Route组件的index prop,如下所示

<Route path="/" element={<App />}>
    <Route index element={<Home />} />
    <Route path='/second' component={secondPage}/>
    <Route path='*' component={NoteDisplay}/>
</Route>
pbpqsu0x

pbpqsu0x3#

<Router>
  <div className="App">
  <Routes>
      <Route path="/*" element={<><Header /><Home /></>} />          
      <Route path="/login" element={<><Login /></>} />
      <Route path="/checkout" element={<><Header /><Checkout /></>} />
  </Routes>
    </div>
</Router>

相关问题