我们如何传递参数this.props.history.push('/page')
在 React-Router v4 中?
.then(response => {
var r = this;
if (response.status >= 200 && response.status < 300) {
r.props.history.push('/template');
});
首先,你不需要做var r = this;
正如这在if statement
指的是回调本身的上下文,因为您使用的是箭头函数,所以它指的是 React 组件上下文。
根据文档:
历史对象通常具有以下属性和方法:
- length - (数字)历史堆栈中的条目数
- action - (字符串)当前操作(PUSH、REPLACE 或 POP)
-
位置 - (对象)当前位置。可能具有以下属性:
- pathname - (字符串)URL 的路径
- search - (string) URL 查询字符串
- hash - (字符串)URL 哈希片段
- state - (字符串)提供给例如的特定于位置的状态Push(path, state) 当这个位置被推送到
堆。仅在浏览器和内存历史记录中可用。
- Push(path, [state]) - (function) 将新条目推送到历史堆栈上
- Replace(path, [state]) - (function) 替换历史堆栈上的当前条目
- go(n) - (函数)将历史堆栈中的指针移动 n 个条目
- goBack() - (函数)相当于 go(-1)
- goForward() - (函数)相当于 go(1)
- block(prompt) - (功能) 阻止导航
因此,在导航时,您可以将道具传递给历史对象,例如
this.props.history.push({
pathname: '/template',
search: '?query=abc',
state: { detail: response.data }
})
或类似地对于Link
组件或Redirect
成分
<Link to={{
pathname: '/template',
search: '?query=abc',
state: { detail: response.data }
}}> My Link </Link>
然后在渲染的组件中/template
路线,您可以访问传递的道具,例如
this.props.location.state.detail
另请记住,当使用 props 中的历史或位置对象时,您需要将组件连接到withRouter
.
根据文档:
带路由器
您可以访问历史对象的属性和最接近的<Route>'s
匹配通过withRouter
高阶分量。withRouter
每次路线改变时都会重新渲染其组件
相同的道具<Route>
render props: { match, location, history }
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)