【问题标题】:Nothing shows up on the screen react router屏幕上什么都没有显示反应路由器
【发布时间】:2022-01-01 17:24:06
【问题描述】:

我有一段时间没有使用 react,我不得不将 react-router-dom 升级到新版本,现在它无法正常工作。我想我改变了我必须升级的一切。屏幕上什么都没有显示它关于路径的东西?我试过用“/”“”有或没有精确。

import './App.css';

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

function App() {
  return (
    <Router>
      <Routes>
        <Route exact path="" component={<p>XD</p>} />
      </Routes>
    </Router>
  );
}

export default App;

【问题讨论】:

    标签: reactjs react-router react-router-dom


    【解决方案1】:

    使用element 代替component

    import './App.css';
    
    import { BrowserRouter as Router, Routes, Route } from "react-router-dom"
    
    function App() {
      return (
        <Router>
          <Routes>
            <Route exact path="/" element={<p>XD</p>} />
          </Routes>
        </Router>
      );
    }
    
    export default App;
    

    【讨论】:

      【解决方案2】:

      react-router-dom 版本 6 中,Route 组件的 componentrenderchildren 函数道具已不复存在,取而代之的是带有 element 的单个 element 道具(i.e. JSX 文字)作为一个值。在 RRDv6 中,所有路由/路径现在也总是完全匹配,因此也不再有 exact 属性。

      <Routes> and <Route>

      declare function Route(
        props: RouteProps
      ): React.ReactElement | null;
      
      interface RouteProps {
        caseSensitive?: boolean;
        children?: React.ReactNode;
        element?: React.ReactElement | null;
        index?: boolean;
        path?: string;
      }
      
      1. 切换到使用 element 属性来渲染路由内容。
      2. 删除 exact 属性,不再需要。

      代码

      <Router>
        <Routes>
          <Route path="/" element={<p>XD</p>} />
        </Routes>
      </Router>
      

      要了解 v5 的其他更改,请参阅 migration guide

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-09
        • 1970-01-01
        • 1970-01-01
        • 2019-01-07
        相关资源
        最近更新 更多