拆分 props.location.search 值

我正在尝试从 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}`

    );

  };

https://img.mukewang.com/64e728a90001fd7a02910031.jpg

正如您所看到的,当我需要选择的值时,数量返回 null


https://img2.mukewang.com/64e728b200011d2401940057.jpg

子衿沉夜
浏览 154回答 1
1回答

米琪卡哇伊

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 valueconst quantity = queryParams.get("quantity");// Ensure it's a number for safetyconst quantityNum = Number(quantity);// ... the rest of your code here
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript