【问题标题】:How to access URL query string values in react router with Redux如何使用 Redux 在反应路由器中访问 URL 查询字符串值
【发布时间】:2016-10-08 07:33:23
【问题描述】:

我有一个如下 URL,其中包含各种查询字符串值。

http://localhost:3000/product/?id=123&name=test

我正在使用 redux 开发同构应用程序,react。所以我正在触发动作,我可以知道如何将这些查询字符串值获取到 redux 动作文件吗?

export function getProductData(params) {

  debug('Action Requested:' + params);  

  return {
    type:    GET_PRODUCT_DATA,
    promise: request.get(API_URL + params.productId)
  }
};

因为在操作中我正在触发 API 调用,并且我需要来自查询字符串值的 ID。

【问题讨论】:

  • 如果您需要在操作中使用响应,则在 ajax 回调中调度而不是在操作中执行承诺。但我不知道这是否是你想要做的。
  • 我的问题是如何访问查询字符串值?如果 url 像 localhost:3000/product/1234,它就像我们在路由器中编码一样工作,例如 /product/:productid

标签: javascript reactjs redux react-router isomorphic-javascript


【解决方案1】:

如果您使用的是 React-router,请继续通过 props.location.query 访问它们

最终看起来像:

const Product = (props) =>
  <div>
     <button onClick={e => props.getProductData(props.location.query)}>Do Some Action</button>
  </div>;

【讨论】:

    【解决方案2】:

    根据您的路由来自 URL 的参数使用 props.params 传播到组件 所以如果你有类似的路线

    <Route path="/product/:productid" component={Product} />
    

    您可以使用 props 从 Product 组件访问 productid 并将其传递给您的操作:

    const Product = (props) =>
      <div>
         <button onClick={e => props.getProductData(props.params)}>Do Some Action</button>
      </div>;
    

    其中props.params 包含您在路由中定义的所有参数。在我们的例子中,productid 的值将在 props.params.productid 中。

    【讨论】:

    • 查询字符串也将成为其中的一部分吗?如果您只有 /product/ 并且 URL 为 /product/?id=1234
    • 这个答案没有解决这个问题。根本没有提到查询字符串的用法。
    猜你喜欢
    • 2017-06-26
    • 2016-07-06
    • 1970-01-01
    • 2022-01-10
    • 2022-01-16
    • 2018-01-14
    • 2017-01-06
    • 2014-08-23
    • 1970-01-01
    相关资源
    最近更新 更多