我正在尝试从 React/Redux 中的 props.location.search 中分离出值。我已成功获得 mixOne 拆分,但我似乎无法返回数量值。这是我的代码: const mixOne = props.location.search ? String(props.location.search.split("mixOne=")[1]) : "None"; const quantity = props.location.search ? Number(props.location.search.split("=")[1]) : 1;这是生成的 URL: const addToCartHandler = () => { props.history.push( `/Cart/${productId}?quantity=${quantity}?mixOne=${mixOne}` ); };正如您所看到的,当我需要选择的值时,数量返回 null
1 回答

米琪卡哇伊
TA贡献1998条经验 获得超6个赞
props.location.search.split("=")
on"?quantity=1?mixOne=Grape"
会返回,[ '?quantity', '1?mixOne', 'Grape' ]
因为 next=
直到 after 之后才会返回mixOne
。
这里有一些不同的修复。
您的查询字符串无效 - a
?
表示查询字符串的开头。&
应使用& 字符分隔单独的参数。它应该看起来像这样:?quantity=1&mixOne=Grape
如果您遵循此处的标准,则可以将其拆分为两种方式:by
=
和 then by&
以获得不同的参数。然而,还有一个更简单的方法。使用新的URLSearchParams API,您可以以可预测的方式解析您的参数:
// Use the constructor with your `props.location.search`
const queryParams = new URLSearchParams(props.location.search);
// Use the getters to grab a specific value
const quantity = queryParams.get("quantity");
// Ensure it's a number for safety
const quantityNum = Number(quantity);
// ... the rest of your code here
添加回答
举报
0/150
提交
取消