gpt4 book ai didi

javascript - react-router v4 嵌套路由问题

转载 作者:行者123 更新时间:2023-11-30 20:19:34 25 4
gpt4 key购买 nike

我有以下情况:

<Wrapper>
<Container>
<Route exact path="/" component={UserListing} />
<Route path="/user/:id" component={UserDetails} />
<Route exact path="(/|/user/\d+)" component={StaticComponent} />
</Container>

<Route path="/create-account" component={CreateAccount}/>
</Wrapper>

好的,所以我的情况很简单:如果路径不等于 "/""/,我不希望 Container 组件呈现用户/:id"。因此,如果路径是 "/create-account",则只有 WrapperCreateAccount 作为子项应该出现,没有 Container

寻求帮助。谢谢

最佳答案

您可以编写一个自定义组件来决定是否像 Container 一样渲染

const RouterRenderer = ({ location, children }) => {
if(location && location.state && location.state.noMatch) {
return null;
}
return children;
}

还有一个子组件告诉这个容器没有匹配的东西

const NoMatch = () => {
return <Redirect to={{state: {noMatch: true}}} />
}
export default withRouter(NoMatch);

现在你可以像这样使用它们了

<Wrapper>
<RouterRenderer>
<Container>
<Switch>
<Route exact path="/" component={UserListing} />
<Route path="/user/:id" component={UserDetails} />
<Route exact path="(/|/user/\d+)" component={StaticComponent} />
<NoMatch />
</Switch>
</Container>
</RouterRenderer>
<Route path="/create-account" component={CreateAccount}/>
</Wrapper>

P.S. Note that its important to use Switch when you are using NoMatch component since you want to render it only when no other route matched. Also you can write RouteRenderer function in the form of an HOC instead of a functional component.

关于javascript - react-router v4 嵌套路由问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51600769/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com