如何在react-router v6中使用element传递props?

cha*_*ess 6 reactjs react-router react-router-dom

我正在尝试将 MainSection 组件重用于两个不同的目的(单个故事和所有故事)。为了实现此目的,我想在转到该组件的渲染的路由中传递一个属性 home。Home 是 true 或 false,我想根据该布尔值渲染 MainSection 组件。但是,当渲染 MainSection 时,I home 始终未定义。链接和路由正在更新 URL,但没有使用我想要的 props 进行渲染。难道我做错了什么?

这是我的路线:

function Routes(){
  return(
    <Switch>
      <Route path="/"  element={<MainSection home={true} />} />
      <Route path="/story" element={ <MainSection home={false} />} />
    </Switch>
  )
}
Run Code Online (Sandbox Code Playgroud)

这是我的 MainSection 组件的代码:

function MainSection({ home }){
  console.log(home)
  return(
    <div className="main-section">
      <BigPicture home={ home }/>
      <Quotes home={ home }/>
    </div>
  )
}
Run Code Online (Sandbox Code Playgroud)

控制台日志不断返回未定义。

谢谢!

Dre*_*ese 11

由于在问题标题中您声明您正在使用react-router-dom版本 6,因此我将对此进行回答。V6不导出Switch组件,而是被Routes组件替代。将 替换SwitchRoutes组件并将Routes组件重命名为其他名称以避免名称冲突。

function MainRoutes(){
  return(
    <Routes>
      <Route path="/" element={<MainSection home />} />
      <Route path="/story" element={<MainSection />} />
    </Routes>
  )
}
Run Code Online (Sandbox Code Playgroud)

从这里开始,home道具应该被视为真实/虚假。您可以双击它以将其强制为严格的布尔值。传递home给子组件也应该没有问题。

function MainSection({ home }) {
  React.useEffect(() => {
    console.log(!!home);
  }, [home]);

  return(
    <div className="main-section">
      <BigPicture home={home} />
      <Quotes home={home} />
    </div>
  )
}
Run Code Online (Sandbox Code Playgroud)

  • @AzharUddinSheikh RRDv6 删除了路线道具。如果您需要访问这些对象的 v6 版本,您将使用 React hooks,“useNavigate”用于替换“history”对象的“navigate”函数,“useParams”用于“params”而不是“match.params”,和“useLocation”用于“位置”。我*强烈*建议查看[迁移指南](https://reactrouter.com/en/v6.3.0/upgrading/v5)以了解从 v5 到 v6 的更改。 (6认同)