繁体   English   中英

使用 React Router v4,如何导航到基于现有浏览器位置但插入新参数的路径?

[英]With React Router v4, how to navigate to a path based upon the existing browser location but with new params interpolated?

目标

如何为父组件中的选择菜单创建 onChange 处理程序以了解子路由的当前位置并推送到替换了路径参数的新路径?

例如……当在 url /users/1/foo/bar ,然后在 html 选择中选择用户 2 时,我想导航到/users/2/foo/bar


当前设置

假设我有以下路线:

<Route path="/users/:userId" component={UserIndex} />

其中有以下子路线:

<Route path="/users/:userId/foo" component={UserFoo} />
<Route path="/users/:userId/foo/bar" component={UserFooBar} />

UserIndex组件中,我有一个 html select 元素,其中包含一个用户列表。

<select onChange={this.changeUser}>
  <option value="1">User 1</option>
  <option value="2">User 2</option>
  <option value="3">User 3</option>
</select>

初次尝试

我尝试在match.path值上使用string.replace()

changeUser = (event) => {
  const { match, history } = this.props
  history.push(match.path.replace(':userId', event.target.value))
}

…但是在呈现选择的UserIndex组件中, match.path的值是/users/:userId ,它不包含userId之后的其余路径:“foo”、“foo/bar”等。


脆弱的工作解决方案

一个脆弱但有效的解决方案是使用location.pathname并按元素编号更新数组的一部分:

changeUser = (event) => {
  const {
    history,
    location,
  } = this.props
  const paths = location.pathname.split('/')
  paths[2] = event.target.value
  history.push(paths.join('/'))
}

但是如果元素编号发生变化怎么办? 确认!


有没有更好、更简单的方法来实现这个目标?

使用来自props.matchprops.location的信息组合

首先,从match提取参数的位置

let position = this.props.match.path.split('/').indexOf(':userId');

使用这个位置,改变位置。

let transformedPath = this.props.location.pathname.split('/')
transformedPath[position] = newValue;
this.props.history.push(trasnformedPath.join('/'))

这是使用 React Router 4 的方法

https://reactrouter.com/core/api/match

  const {
    props.params: { userId },
  } = match;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM