首页 > 解决方案 > 如何在闪电组件salesforce中获取查询字符串参数

问题描述

我正在尝试从当前页面获取 url 查询字符串参数,并且我有以下代码:

doInit: function (component, event, helper) {
    var urlParams = new URLSearchParams(window.location.search);
    console.log("params::: ", urlParams);
    if (urlParams.has("openSidebar") && urlParams.get("openSidebar") == true) {
      console.log("redirection happening....");

      component.set("v.showFeed", true);
      component.set("v.isSidebarOpen", true);
    }
  },

由于某种原因,我似乎无法使用这一行var urlParams = new URLSearchParams(window.location.search); 我不知道为什么。

是否有任何替代或销售人员方式从 url 获取查询字符串参数?

我基本上什么也没得到,执行似乎停止在我使用URLSearchParams的那一行!

也很想知道为什么闪电在这种情况下不让普通的 javascript 执行?

标签: javascriptsalesforcesalesforce-lightningsalesforce-communities

解决方案


Usingnew URLSearchParams将返回一个类的实例,而不是一个对象(或映射)。

您可以使用此代码将键/对值转换为对象。然后您可以检查对象上的值:

const searchParams = new URLSearchParams('?openSidebar=true&foo=bar&test=hello%26world')
const params = [...searchParams.entries()].reduce((a, [k, v]) => (a[k] = v, a), {})
console.log(params)


if (params.openSidebar === 'true') {
  console.log("redirection happening....");
  // do stuff here      
}

请注意,我们之所以使用=== 'true'url 参数,是因为它始终是一种字符串。

既然您说它不起作用,您可以构建自己的解析器:

const qs = '?openSidebar=true&foo=bar&test=hello%26world'
  .slice(1) // remove '?'

const d = decodeURIComponent // used to make it shorter, replace d with decodeURIComponent if you want
const params = qs
  .split('&') // split string into key/pair
  .map(s => s.split('=')) // split key/pair to key and pair
  .reduce((a, [k, v]) => ((a[d(k)] = d(v)), a), {}) // set each object prop name to k, and value to v

console.log(params)

请注意,我们使用decodeURIComponent()(或简写d()last,因为参数可能包含与号或等号。如果我们d()先打电话,我们会分裂这些角色,这是我们不希望发生的。


推荐阅读