gpt4 book ai didi

reactjs - 如何在react-router v4中使用history.push/Link/Redirect传递参数?

转载 作者:行者123 更新时间:2023-12-03 12:52:14 25 4
gpt4 key购买 nike

如何在 React-Router v4 中使用 this.props.history.push('/page') 传递参数?

.then(response => {
var r = this;
if (response.status >= 200 && response.status < 300) {
r.props.history.push('/template');
});

最佳答案

首先,你不需要做var r = this;就像 if statement 中的那样指的是回调本身的上下文,因为您使用的是箭头函数,所以它指的是 React 组件上下文。

根据文档:

history objects typically have the following properties and methods:

  • 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) The path of the URL
    • search - (string) The URL query string
    • hash - (string) The URL hash fragment
    • state - (string) location-specific state that was provided to e.g. push(path, state) when this location was pushed onto the stack. Only available in browser and memory history.
  • push(path, [state]) - (function) Pushes a new entry onto the history stack
  • replace(path, [state]) - (function) Replaces the current entry on the history stack
  • go(n) - (function) Moves the pointer in the history stack by n entries
  • goBack() - (function) Equivalent to go(-1)
  • goForward() - (function) Equivalent to go(1)
  • block(prompt) - (function) Prevents navigation

因此,在导航时,您可以将 Prop 传递给历史对象,例如

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 渲染的组件中路线,您可以访问传递的 Prop ,例如

this.props.location.state.detail

另请记住,当使用 props 中的历史或位置对象时,您需要使用 withRouter 连接组件。 .

根据文档:

withRouter

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 }.

关于reactjs - 如何在react-router v4中使用history.push/Link/Redirect传递参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44121069/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com