如何在 react-router v4 中通过 history.push/Link/Redirect 传递参数?

新手上路,请多包涵

我们如何在 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');
          });

原文由 IshanGarg 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 377
1 个回答

首先,你不需要做 var r = this; 因为 this in if statement 指的是回调本身的上下文,因为你使用箭头函数指的是 React 组件上下文。

根据文档:

history 对象通常具有以下属性和方法:

  • length - (number) 历史堆栈中的条目数

  • action -(字符串)当前操作(PUSH、REPLACE 或 POP)

  • location - (object) 当前位置。可能具有以下属性:

    • pathname - (string) URL 的路径
    • search - (string) URL 查询字符串
    • hash - (string) URL 哈希片段
    • state -(字符串)特定于位置的状态,当此位置被推入堆栈时提供给例如 push(path, state)。仅在浏览器和内存历史记录中可用。
  • push(path, [state]) - (function) 将新条目推送到历史堆栈

  • replace(path, [state]) - (function) 替换历史堆栈中的当前条目

  • go(n) - (function) 将历史堆栈中的指针移动 n 个条目

  • goBack() - (function) 相当于 go(-1)

  • goForward() - (function) 相当于 go(1)

  • block(prompt) - (function) 阻止导航

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

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 连接。

根据文档:

与路由器

您可以通过 withRouter 高阶组件访问历史对象的属性和最接近的 <Route>'s 匹配项。 withRouter 每次使用与 <Route> render props: { match, location, history } 相同的道具时,将重新渲染其组件。

原文由 Shubham Khatri 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进