目标
如何在父组件中为选择菜单创建一个onChange处理程序,以了解子路由的当前位置并推送到替换了路径参数的新路径?
例如……当在URL /users/1/foo/bar
上,然后在html select中选择用户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>
初次尝试
我尝试在
string.replace()
值上使用match.path
: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('/'))