[英]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.match
和props.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.