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组件替代。将 替换Switch为Routes组件并将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)
| 归档时间: |
|
| 查看次数: |
22291 次 |
| 最近记录: |