【问题标题】:How can I preserve a single query string value between routes in React Router?如何在 React Router 中的路由之间保留单个查询字符串值?
【发布时间】:2017-06-18 11:33:02
【问题描述】:

即使在路由之间导航时,我也希望将locale=en-US 保留在查询字符串中。我希望我的其余代码完全不知道locale=en-US 查询字符串值,并在我使用<Link> 时自动传递它。我该怎么做?

【问题讨论】:

标签: reactjs react-router


【解决方案1】:

我了解到 React Router 不提供开箱即用的此功能,但可以按照 @michal-cumpl 的建议创建自定义 Link 组件,如下所示:

import { Link as ReactRouterLink } from 'react-router'
import React, { Component } from 'react'
import merge from 'merge'
import url from 'url'

const QUERY_PARAMS_TO_PRESERVE = ['locale', 'foo', 'bar']

const makeToObj = (to, query) => {
  if (typeof to === 'string') {
    const u = url.parse(to, true)
    to = {
      pathname: u.pathname,
      query: u.query,
      hash: u.hash,
    }
  }

  if (to.query) {
    to.query = merge(query, to.query)
  } else {
    to.query = query
  }

  return to
}

class Link extends Component {
  render() {
    const currentQuery = url.parse(window.location.href, true).query
    const queryToPreserve = {}
    QUERY_PARAMS_TO_PRESERVE.forEach(x => queryToPreserve[x] = currentQuery[x])

    const to = makeToObj(this.props.to, queryToPreserve)

    return (
      <ReactRouterLink to={to}>
        {this.props.children}
      </ReactRouterLink>
    )
  }
}

export { Link }
export default Link

请注意,当使用与 React Router 集成的第三方工具(例如 react-router-bootstrap 的 LinkContainer)时,这会中断。

【讨论】:

    【解决方案2】:

    为此,您可以将以下对象传递给Link to 属性:

    • pathname:表示链接路径的字符串。
    • query:要字符串化的键值对对象。
    • hash:要放入 URL 的哈希值,例如#a 哈希。

    然后您可以编写一个组件,该组件将从window.location.href 读取和解析查询字符串并呈现Link

    https://github.com/ReactTraining/react-router/blob/master/docs/API.md#link

    【讨论】:

    • 我担心我必须编写一个自定义的Link 组件。请参阅下面我自己的答案以获取我的解决方案。
    • 这种方法在你使用例如 react-router-bootstrap 的 LinkContainer 时会失效。我认为真的需要它在 React Router 本身中。
    • 向后/向前导航怎么样?
    猜你喜欢
    • 2017-05-13
    • 2016-09-15
    • 1970-01-01
    • 2017-08-14
    • 1970-01-01
    • 2017-09-22
    • 2016-06-20
    • 1970-01-01
    • 2019-12-11
    相关资源
    最近更新 更多