有可能从React路由中获得密钥以传入组件吗



我的目标是编辑表单和添加表单,现在我的问题是当我点击"编辑"按钮时,它成功地显示了,但当按下"添加新"按钮时它会呈现以前的数据。

目前,我正在尝试在我的react应用程序中使用不同的路线,但在相同的组件中添加/编辑表单,如下所示:

<>
<Switch>
<Route key="add" path={`${match.url}/new`} component={AgenciesUpdatePage} />
<Route key="edit" path={`${match.url}/:id/edit`} component={AgenciesUpdatePage} />
<Route path={`${match.url}/:id`} component={AgenciesViewPage} />
<Route path={match.url} component={AgenciesListPage} />
</Switch>
</>

我如何在我的组件上传递(密钥(,因为根据我的理解,密钥是区分同一组件的两个路径所必需的。

否则,如果你有其他解决方案,我想看看。

路由中key道具的用途是用于组件映射。AgenciesUpdatePage将无法使用您当前的实现访问其值。

将您的路线更改为以下路线:

<Route path={`${match.url}/new`} component={() => <AgenciesUpdatePage action="add" />} />
<Route path={`${match.url}/:id/edit`} component={() => <AgenciesUpdatePage action="edit" />} />

然后更新您的AgenciesUpdatePage组件以使用新实现的action道具。

您可以在AgenciesUpdatePage中使用以下内容访问它:

const AgenciesUpdatePage = ({ action }) => {
if (action === 'add') // Render or do something
if (action === 'edit') // Render or do something
return (...)
}

最新更新