当我点击链接时,我使用了 React-router 来重定向我的页面,但它没有重定向

问题描述 投票:0回答:2

这是我的app.js

import React from 'react'
import Quote from './components/Quote';
import './index.css'
import Abraham from './components/Abraham'

import {
  BrowserRouter as Router,
  Routes,
  Route,
  Link
} from "react-router-dom";
function App() {
  

  return (
<>
    <div>
      <Quote/>
      <h2>List of authors</h2>
      
    </div>
    <Router>
    <div>
    <Link to="/">Author1</Link>
    </div>
    <Routes>
      <Route exactpath="/" 
        element={ <Abraham/>} />
      
    </Routes>
    </Router>
</>


  )
}
export default App;

这是我的 abraham.js

import React from 'react'

export default function Abraham() {
  return (
    <div>
      <h1>My name is Abraham</h1>
    </div>
  )
}

当我点击作者 1 时,我想重定向到亚伯拉罕,但它没有发生 该页面没有重定向,我使用 React router dom 将其链接到另一个页面,即我导入的 Abraham

reactjs react-router
2个回答
1
投票

我认为你错过了

exact path
之间的空格, exactpath 道具应该写成 exact path ,它们之间有一个空格。请参阅文档:https://v5.reactrouter.com/web/api/Route/exact-bool

import React from 'react'
import Quote from './components/Quote';
import './index.css'
import Abraham from './components/Abraham'

import {
  BrowserRouter as Router,
  Routes,
  Route,
  Link
} from "react-router-dom";

function App() {
  return (
    <>
      <div>
        <Quote/>
        <h2>List of authors</h2>
      </div>
      <Router>
        <div>
          <Link to="/">Author1</Link>
        </div>
        <Routes>
          <Route exact path="/" element={<Abraham />} />
        </Routes>
      </Router>
    </>
  )
}

export default App;

0
投票

如果您希望

Abraham
路由和组件与
Quote
组件和
h2
元素分开渲染,那么您应该将后者放置在路由上,以便它们也根据 URL 路径有条件地渲染。

React-Router v6 中的

exact
组件没有
Route
属性,应该将其删除,因为现在所有路由都使用 路由排名 分数始终 完全匹配。

示例:

import {
  BrowserRouter as Router,
  Routes,
  Route,
  Link
} from "react-router-dom";

function App() {
  return (
    <Router>
      <Routes>
        <Route
          path="/"
          element={(
            <div>
              <Quote />
              <h2>List of authors</h2>
              <div>
                <Link to="/abraham">Author1</Link>
              </div>
            </div>
          )}
        />
        <Route path="/abraham" element={<Abraham />} />
      </Routes>
    </Router>
  );
}
© www.soinside.com 2019 - 2024. All rights reserved.