嵌套 React Router:在显示嵌套子组件时隐藏父组件

Nested React Router : hide parent component on showing nested child component

作为reactJS的初学者,我想知道如何在路由到子组件时隐藏父组件URL

假设一个场景:

用户在“/house”是这样的:

<Route path="/house" component={House} />

当用户点击房屋网格时,他导航到“/house/flat/:flatID”。内部房屋组件

<Route
    path={`${this.props.match.url}/flat/:flatId`}
    render={() => <div>Each Flat details</div>}
/>

那么子组件和父组件都是可见的,如下所示:

所以我想要的是当用户导航到“/house/flat:FlatId”时只显示平面组件。请给我任何有帮助的建议!文章的任何链接,以便我可以学习和实现此类功能。

代码:

App.js

<Switch>
    <Route exact path="/" component={Home} />
    <Route exact path="/account" component={Account} />
    <Route path="/gharjagga" component={GharJagga} />
</Switch>

House.js

onGharGridClick= id => {
    <Redirect to={`${this.props.match.url}/flat/${id}`} />;
};

return (
    <Route
        path={`${this.props.match.url}/flat/:fkatId`}
        render={() => <div>Ghar Each</div>}
    />
);

解决方案是将 "/house/flat/:flatId" 提高到与 "/house" 相同的水平。

<Switch>
  <Route exact path="/" component={Home} />
  <Route path="/account" component={Account} />
  <Route path="/house/flat/:flatId" render={() => <div>Each Flat details</div>}/>
  <Route path="/house" component={House} />
</Switch>

您可以通过不同的方式实现它

  1. 在父组件中定义路由,我认为这是最好的选择。
<Switch>
  <Route path="/account" component={Account} />
  <Route path="/house/flat/:flatId" component={FlatComponent}/>
  <Route path="/house" component={House} />
  <Route path="/" component={Home} />
</Switch>

注意:不要使用 exact,而是根据优先级对路由进行排序,如果输入的路由中有任何拼写错误,路由将重定向到下一个匹配的路由

  1. 您可以将 House 作为单独的路由组件,并将路由嵌套在该组件中
// Routes
<Switch>
  <Route path="/account" component={Account} />
  <Route path="/house" component={House} />
  <Route path="/" component={Home} />
</Switch>

// House component
class House extends React. Components {
  render() {
    return (
      <Switch>
        <Route path="/house/flat/:flatId" render={() => <div>Each Flat details</div>} />}/>
        <Route path="/house" component={HouseGridComponent} />
      </Switch>
    )
  }
}
  1. 你可以检查路线是否有flatId并隐藏元素,在你的House组件中你可以检查this.props.match.params.flatId,如果设置了flatId你可以隐藏那个House组件.
// House Component

class House extends React. Components {
  render() {
    return (
      <div>
        {
          !this.props.match.params.flatId?
            <h1>House Component</h1>:
            null
        } 

        <Route path={`${this.props.match.url}/flat/:flatId`} render={() => <div>Each Flat details</div>} />
      </div>
    )
  }
}