如何在闪电组件 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执行?

使用new 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()(最后,因为参数可能包含与号或等号。如果我们先打电话给d(),我们会在这些角色上分裂,我们不希望发生这种情况。

URLSearchParams(( 在我的浏览器上也不起作用,但我想出了一个帮助函数来完成工作。

function getURLSearchParameters() {
const urlSearchParameters = {};
let searchParameters = decodeURIComponent(window.location.search);
if (searchParameters !== '') {
searchParameters = searchParameters.substring(1).split('&'); // get ride of '?'
for (let i = 0; i < searchParameters.length; i++) {
[key, value] = searchParameters[i].split('=');
urlSearchParameters[key] = value;
}
}
return urlSearchParameters;
}

不幸的是,我无法回答您的其他问题,因为我没有任何使用salesforce的经验

最新更新