【问题标题】:Function component on the same page in not picking in route (react-router-dom v6) of react project同一页面上的功能组件在 react 项目的路由(react-router-dom v6)中不选择
【发布时间】:2021-12-26 10:28:48
【问题描述】:

我使用 react-router-dom 版本 6.2.1 的方法在我的 react 项目中创建了一个路由。

但是当我试图获取写在同一个实现组件上的功能组件的一个路由时,它不起作用。

App.js

import React from 'react';
import './App.css';
import {Routes ,Route} from 'react-router-dom';
import HomePage from './pages/homepage/homepage.component';

const CarsPage= () => {
  <div>
    <h1>CARS PAGE</h1>
  </div>
}

function App() {
  return (
   <div>
     <Routes >
       <Route exact path='/' element={<HomePage />} />
       <Route exact path='/cars' element={<CarsPage/>} /> // This route is not working.
     </Routes>
   </div>
  );
}

export default App;

问题

帽子路线没有好转。

【问题讨论】:

    标签: javascript reactjs react-router


    【解决方案1】:

    您忘记了 CarsPage 中的 return 声明

    改成:

    const CarsPage= () => {
      return (
      <div>
        <h1>CARS PAGE</h1>
      </div>
    )
    }
    

    【讨论】:

      【解决方案2】:

      您需要将组件包装在 BrowserRouter 中。 在这里查看一切正常:https://codesandbox.io/s/festive-leavitt-7tr1d?file=/src/App.js

      【讨论】:

      • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
      【解决方案3】:

      看上面的实现,CarsPage 组件没有返回任何东西。重构它以像这样返回您的 JSX。

      const CarsPage = () => (
          <div>
            <h1>CARS PAGE</h1>
          </div>
      );
      

      另外,从"react-router-dom" 导入BrowserRouter 并用BrowserRouter 包装“react-router-dom”组件BrowserRouter,就像在docs 中看到的那样

      import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
      
      ...
      
      function App() {
        return (
          <div>
            <Router>
              <Routes>
                <Route exact path="/" element={<HomePage />} />
                <Route exact path="/cars" element={<CarsPage />} />
              </Routes>
            </Router>
          </div>
        );
      }
      
      

      【讨论】:

        猜你喜欢
        • 2022-11-29
        • 2022-08-02
        • 2021-10-21
        • 2021-11-03
        • 2022-07-09
        • 2022-06-23
        • 2022-03-23
        • 2022-10-12
        • 2022-01-09
        相关资源
        最近更新 更多