React URL param redirect

问题描述 投票:0回答:1

我目前正在与 反应反应路由器 而我正在构建一个页面,显示某个项目的详细信息,当页面挂载时,该项目从API中获取数据。fetch方法需要项目的 id 所以我用 match.params.id 来获取fetch方法的值。我也在使用 蛞蝓 包,在后端以URL格式显示该项目标题,并与 id. 我希望用户能够输入带有slug标题的URL,而不用担心输入的是什么。id 以便被引导到具有正确数据的页面。

例如,点击UI上的项目会使URL看起来像这样。localhost:3000/the-title-slug/123456.你必须实际点击UI上的项目才能得到有id的URL,但我想让用户更简单,让他们只输入slug标题,就能重定向到有该slug和id的正确URL。localhost:3000/the-slug-title,它将重定向到正确的URL与该slug和id。

有什么办法可以做到这一点吗?有点像如果你输入 googel.com 它纠正了打字错误,并引导你到 google.com. 如果有任何帮助弄清楚这个问题,我将非常感激,谢谢你。

reactjs url react-router url-parameters
1个回答
0
投票

你的后端必须有API方法来获取正确的项目,通过拼写错误的slug.like。

requestData: the-slug-title
responseData: the-title-slug, 123456

然后你的组件必须处理错误的url

componentDidMount() {
  const { params } = this.props.match;

  const respose = await fetch({ ... })

  this.setState({ id: response.id, slug: response.slug });
}

render() {
  const { params } = this.props.match;

  return this.state.id && this.state.slug && (this.state.id !== params.id || this.state.slug !== params.slug) && <Redirect to={`/${this.state.slug}/${this.state.id}`} />
}
© www.soinside.com 2019 - 2024. All rights reserved.