【问题标题】:How to pass props using element in react-router v6?如何在 react-router v6 中使用元素传递道具?
【发布时间】:2022-01-23 08:32:02
【问题描述】:

我正在尝试将 MainSection 组件用于两个不同的目的(单个故事和所有故事)。为了实现这一点,我想在路由中传递一个属性 home,该属性用于该组件的渲染。 Home 是真还是假,我想根据该布尔值呈现 MainSection 组件。但是,当 MainSection 被渲染时,我的家一直未​​定义。链接和路由正在更新 URL,但没有使用我想要的道具进行渲染。我做错了吗?

这是我的路线:

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

这是我的 MainSection 组件的代码:

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

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

谢谢!

【问题讨论】:

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


    【解决方案1】:

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

    function MainRoutes(){
      return(
        <Routes>
          <Route path="/" element={<MainSection home />} />
          <Route path="/story" element={<MainSection />} />
        </Routes>
      )
    }
    

    从这里开始,home 属性应该被视为真/假。您可以对其进行双重打击以将其强制为严格的布尔值。将home 传递给子组件也应该可以正常工作。

    function MainSection({ home }) {
      React.useEffect(() => {
        console.log(!!home);
      }, [home]);
    
      return(
        <div className="main-section">
          <BigPicture home={home} />
          <Quotes home={home} />
        </div>
      )
    }
    

    【讨论】:

    • 谢谢德鲁!没想到 Switch 已经出局了。
    猜你喜欢
    • 2022-01-12
    • 1970-01-01
    • 1970-01-01
    • 2022-07-21
    • 2018-04-27
    • 1970-01-01
    • 2018-11-20
    • 2015-07-18
    • 2022-09-23
    相关资源
    最近更新 更多