亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

拆分 props.location.search 值

拆分 props.location.search 值

子衿沉夜 2023-08-24 17:52:48
我正在嘗試從 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。

這里有一些不同的修復。

  1. 您的查詢字符串無效 - a?表示查詢字符串的開頭。&應使用& 字符分隔單獨的參數。它應該看起來像這樣:?quantity=1&mixOne=Grape

  2. 如果您遵循此處的標準,則可以將其拆分為兩種方式:by=和 then by&以獲得不同的參數。然而,還有一個更簡單的方法。

  3. 使用新的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


查看完整回答
反對 回復 2023-08-24
  • 1 回答
  • 0 關注
  • 183 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號