javascript - 当我在路由中使用渲染时 react 返回 Outlet 组件

标签 javascript reactjs react-router react-router-dom

我正在尝试将 react-router 与 props id 一起使用,但它给了我以下信息:

Matched leaf route at location "/some-12" does not have an element. This means it will render an <Outlet /> with a null value by default resulting in an "empty" page.

我正在使用 "react-router-dom": "6"和 "react": "^17.0.2"

//example Routes
import {Route, Routes } from "react-router-dom";
function App()
return(
   <>
   <Routes>
      <Route path="/about" element={<About />}/>
      <Route exec={true} path="/something" element={<Something/>}/>
      <Route exact={true} path="/something-:id"
             render={(props) => {
             <Some id={props.match.params.id} />;}}
       />
      <Route path="/contact" element={<Contact />}/>
   </Routes>
   </>```
//example Some
export default function Some({ id }) {
    return(
       <>
          <p>Some with id: {id}
       </>
    )}

我哪里做错了?

最佳答案

react-router-dom 版本 6 中,Route 组件在 element 属性上呈现所有路由组件,并且不再有任何路由 props,即没有 historylocationmatch

element 属性上渲染 Some 组件并使用 useParams 钩子(Hook)访问 id 路由匹配参数。如果 path="/something-:id" 不起作用,请尝试将 id 设为自己的路径段,即 path="/something/:id ".

function App()
  return(
    <>
      <Routes>
        <Route path="/about" element={<About />}/>
        <Route path="/something" element={<Something/>}/>
        <Route path="/something-:id" element={<Some />} />
        <Route path="/contact" element={<Contact />}/>
      </Routes>
    </>
  );
}

...

import { useParams } from 'react-router-dom';

export default function Some() {
  const { id } = useParams();
  return(
    <>
      <p>Some with id: {id}
    </>
  );
}

关于javascript - 当我在路由中使用渲染时 react 返回 Outlet 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70438795/

相关文章:

javascript - React 组件不工作

javascript - 在 getDefaultProps 中缓存 Prop 是 React 中的反模式?

reactjs - react 路由器索引路由不显示为默认

javascript - 将 props 传递给 react-router v4 中的路由器组件

javascript - 为什么console.log有时会打印出已导出的变量未定义?

javascript - 如何在 AngularJS Controller 内定义普通的 JavaScript 函数

javascript - 如何隐藏特定 slider 上的 NEXT 按钮

javascript - 如何同时运行两个 jQuery 动画?

reactjs - 找不到名称 'fetch'

reactjs - URL 更改无需在 React 路由器中重新渲染