如何在 react-router v4 中使用 history.push/Link/Redirect 传递参数? [英] How to pass params with history.push/Link/Redirect in react-router v4?
问题描述
我们如何在 React-Router v4 中使用 this.props.history.push('/page')
传递参数?
How can we pass parameter with this.props.history.push('/page')
in React-Router v4?
.then(response => {
var r = this;
if (response.status >= 200 && response.status < 300) {
r.props.history.push('/template');
});
推荐答案
首先,你不需要做 var r = this;
as this in if statement
指向回调本身的上下文,因为您使用的是箭头函数,因此引用了 React 组件上下文.
First of all, you need not do var r = this;
as this in if statement
refers to the context of the callback itself which since you are using arrow function refers to the React component context.
history 对象通常具有以下属性和方法:
history objects typically have the following properties and methods:
- length - (number) 历史堆栈中的条目数
- action - (字符串)当前操作(PUSH、REPLACE 或 POP)
location - (object) 当前位置.可能具有以下属性:
- length - (number) The number of entries in the history stack
- action - (string) The current action (PUSH, REPLACE, or POP)
location - (object) The current location. May have the following properties:
- pathname - (string) URL 的路径
- search - (string) URL 查询字符串
- hash - (字符串)URL 哈希片段
- state -(字符串)提供给例如的特定于位置的状态push(path, state) 当这个位置被推到堆.仅在浏览器和内存历史记录中可用.
因此,在导航时,您可以将道具传递给历史对象,例如
So while navigating you can pass props to the history object like
this.props.history.push({
pathname: '/template',
search: '?query=abc',
state: { detail: response.data }
})
或类似的对于 Link
组件或 Redirect
组件
or similarly for the Link
component or the Redirect
component
<Link to={{
pathname: '/template',
search: '?query=abc',
state: { detail: response.data }
}}> My Link </Link>
然后在使用 /template
路由渲染的组件中,您可以访问像
and then in the component which is rendered with /template
route, you can access the props passed like
this.props.location.state.detail
还要记住,当使用 props 中的 history 或 location 对象时,您需要将组件与 withRouter
连接起来.
Also keep in mind that, when using history or location objects from props you need to connect the component with withRouter
.
withRouter
您可以访问历史对象的属性和最近的
通过 withRouter
高阶组件匹配.withRouter
每次路由随着与
渲染相同的 props props: { match, location, history }
.
You can get access to the history object’s properties and the closest
<Route>'s
match via the withRouter
higher-order component. withRouter
will re-render its component every time the route changes with the
same props as <Route>
render props: { match, location, history }
.
这篇关于如何在 react-router v4 中使用 history.push/Link/Redirect 传递参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!