javascript - 如何在闪电组件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 执行?
解决方案
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()
先打电话,我们会分裂这些角色,这是我们不希望发生的。
推荐阅读
- firebase - 带有 FireStore 的 Flutter 聊天模块
- excel - 如何使用 VBA 和选择器将此网站的内容转换为 Excel?
- postgresql - 使用气流的 postgres 数据库获取应用程序数据
- numpy - 迭代数组列并垂直堆叠它们的最快方法
- reactjs - 在 React-css 中,Bootstrap 影响另一个类组件
- docker - docker run dynamodb-local on Github Actions Workflow 挂起
- netbeans - 从 Ant 切换到 Maven 时 Netbeans 中的问题
- python - Pyspark - 如何根据两条线的差异创建新线
- java - 无法从android客户端连接到在windows上运行的python服务器
- python - 如何在我的 Pandas 数据框中合并绝对值?