使用 react-router v4 进行路由的问题

Issues with routing with react-router v4

我有一个 Home.jsx 组件,它有路由 "/".

当用户单击列表的项目时,列表本身应该消失,具有指定用户详细信息的组件应该出现,例如"/user/1".

当单击 back 按钮或基本上在页眉上时,它应该返回到 "/" 并再次显示列表。

我的做法: 我基本上所做的是:

首先,路线(在App.jsx):

<Route exact path="/" component={Home}/>
<Route path="/user/:id" component={Home}/>

然后,里面Home.jsx我在玩道具:

if (this.props.match.path === '/') {
   return <UserList />;
} else {
   return <UserDetails userId={userId} />
}

但是 不幸的是 - 我的 Home.jsx 组件正在 安装 每次路径更改 - 从 "/""/user/:id" 并向前。因此,如果它重新安装,每个子组件也会重新安装,这会导致每个道具重新加载,从而导致我的应用程序崩溃...

非常感谢任何反馈或帮助如何解决该问题,如何阻止它在每次路径更改时重新安装。谢谢。

<Route /> 组件的全部意义在于处理您的 if 语句正在做的事情:根据 url.

有条件地渲染组件

您希望主页组件在 //user/:id 上呈现,而不是完全在 / 上呈现。

您的 App.js 文件应如下所示:

<Route path="/" component={Home} />

在你的 Home.js 文件中而不是带有 if 语句的函数,只渲染 <Route /> 个组件。

你可能有类似的东西

<div>
   {this.figureOutWhichComponentToShow()}
   <StaticContent />
</div>

将其更改为:

<div>
   <Route exact path="/" component={UserList} />
   <Route path="/user/:id" component={UserDetails} />
   <StaticContent />
</div>

并在 UserDetails 组件中使用 this.props.match.params.id。或者您可以将其内联到 Route

<div>
   <Route exact path="/" component={UserList} />
   <Route path="/user/:id" component={props => 
     <UserDetails userId={props.match.params.id} /> 
   }/>
   <StaticContent />
</div>