如何在 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;
因为 if 语句
中的 this 是指到回调本身的上下文,因为你使用箭头函数是指 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 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 - (string) 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 中的历史或位置对象时,您需要将组件与 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
每次路由更改时都会重新渲染其组件与 <Route>
渲染相同的道具 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屋!