React子组件Sidebar向父组件Dashboard传值切换页面失效如何解决?
问题根因
- 父组件
RenderComponent的switch分支缺少profile匹配项,点击profile按钮时会进入default逻辑返回字符串foo,无法渲染对应页面;如果archived页面也无法渲染,大概率是变量遮蔽问题:RenderComponent的形参与父组件state变量param重名,传参过程中可能出现取值错误。 - 子组件
SideBar单独维护了一份选中状态,和父组件状态不一致,属于冗余逻辑,后续做按钮高亮等交互时容易出问题。
解决步骤
步骤1:修正父组件RenderComponent逻辑
直接引用父组件的param状态,不需要传参,避免变量遮蔽,同时补充profile分支:
// 去掉形参,直接使用外层的param state const RenderComponent = () => { switch (param) { case "created": return ( <> <AddButton /> <PortfolioList /> </> ); case "archived": return <Archived />; case "profile": // 确保你已经正确引入Profile组件 return <Profile />; default: return "foo"; } };
步骤2:修改RenderComponent调用方式
不需要再传参:
<> <Left> <SideBar changeParam={changeParam} /> </Left> <Middle>{RenderComponent()}</Middle> </>
(可选)优化子组件冗余状态
子组件不需要单独维护选中状态,直接从父组件传入当前选中值即可,方便做按钮高亮等交互:
父组件传参:
<SideBar changeParam={changeParam} currentParam={param} />
子组件修改后代码:
function SideBar({ changeParam, currentParam }) { const handlePage = (page) => { changeParam(page); }; return ( <Container> <Button onClick={() => handlePage("archived")} // 可直接用父组件传的值判断是否选中 active={currentParam === "archived"} > 归档 </Button> <Button onClick={() => handlePage("profile")} active={currentParam === "profile"} > 个人资料 </Button> </Container> ); }
内容的提问来源于stack exchange,提问作者Roger Staxx
相关产品推荐
相关产品推荐

