【问题标题】:How to correctly set/read query param in url?如何正确设置/读取 url 中的查询参数?
【发布时间】:2020-03-31 05:36:05
【问题描述】:

我使用 React,我有过滤器组件,它有一些表单元素,例如复选框、输入、选择和我当我单击按钮“应用过滤器”时我想将来自过滤器的数据保存在 URL 中,然后在重新加载页面后只需从那里阅读即可。

我使用useQueryParams 在 URL 中设置数据。例如 filter/shop=ball&shop=phone&shop=apple

如何以正确的 JS 数据类型翻译 URL。可能有人知道它的一些 npm 包。

例如我有 url filter/shop=ball&shop=phone&shop=apple&count=123&name=example

我想得到一个像

这样的对象
{
shop: [ball,phone,apple],
count:123,
name:'example"
}

感谢您的帮助

【问题讨论】:

标签: javascript reactjs url query-parameters


【解决方案1】:
function parseQuery() {
  const qs = window.location.search.replace('?', '')
  const items = qs.split('&')
  return items.reduce((data, item) => {
    const splittedItem = item.split('=')
    const key = splittedItem[0]
    const value = splittedItem.length > 2 ? window.decodeURIComponent(splittedItem.slice(1).join('=')) : splittedItem[1]
    if(data[key] !== undefined) {
      if(!Array.isArray(data[key])) {
        data[key] = [ data[key] ]
      }
      data[key].push(value)
    } else {
      data[key] = value
    }

    return data
  }, {})
}

【讨论】:

    猜你喜欢
    • 2021-07-26
    • 1970-01-01
    • 1970-01-01
    • 2015-02-11
    • 2018-09-09
    • 2019-03-06
    • 1970-01-01
    • 1970-01-01
    • 2020-12-10
    相关资源
    最近更新 更多