簡體   English   中英

React & Axios - 動態地將鍵和值添加到 object

[英]React & Axios - Dynamically add key and value to object

在我的一個小項目上工作並遇到了一個問題。 我正在使用“ASOS”API,我需要動態地將鍵和值添加到它需要找到正確產品的參數中。 例如選擇顏色、尺寸、價格范圍等。問題是,我嘗試過的所有事情都沒有成功。

如何動態地將鍵和值添加到 object?

像這樣的東西:

currency: "USD",
sizeSchema: "US",
lang: "en-US",
newKey: newValue

這是我的代碼:

const FetchAPI = (props) => {
  const [product, setProducts] = useState([]);
  // Key and Value
  let facetKey = props.facetKey;
  let facetValue = props.facetValue;

// Sets the paramaters
  let params = {
    store: "US",
    offset: props.offset,
    categoryId: props.categoryId,
    limit: props.limit,
    country: "US",
    sort: "freshness",
    currency: "USD",
    sizeSchema: "US",
    lang: "en-US",
  };
  // Need to add my "facetKey" and "facetValue" to "params".

  useEffect(() => {
    const options = {
      method: "GET",
      url: "https://asos2.p.rapidapi.com/products/v2/list",
      params: params,
      headers: {
        "x-rapidapi-key": "",
        "x-rapidapi-host": "",
      },
    };

    axios
      .request(options)
      .then(function (response) {
        setProducts(response.data.products);
        props.items(response.data.itemCount);
        props.facets(response.data.facets);
        console.log(response.data.facets);
      })
      .catch(function (error) {
        console.error(error);
      });
  }, [props.offset, props.limit]);

  return (
    <div>
      <div className={classes.container}>
        {product.map((product) => (
          <ProductCard
            key={product.id}
            img={product.imageUrl}
            name={product.name}
            price={product.price.current.text}
          />
        ))}
      </div>
    </div>
  );
};

謝謝!

記住facetKeyfacetValue返回字符串值,如果用戶沒有選擇“facet”,或者過濾產品的選項。 然后返回undefined ,當然可以把這個改成 null。

您可以將[]運算符用於對象。

一般來說:

 let obj = {}; let key = 'x'; let value = 3; obj[key] = value; console.log(obj); console.log(obj[key]);

在您的示例中:

let facetKey = props.facetKey;
let facetValue = props.facetValue;

// Sets the paramaters
let params = {
  // ...
};
// Need to add my "facetKey" and "facetValue" to "params".

if (facetKey)
  params[facetKey] = facetValue;

您可以編寫如下代碼。

let params = {
    store: "US",
    offset: props.offset,
    categoryId: props.categoryId,
    limit: props.limit,
    country: "US",
    sort: "freshness",
    currency: "USD",
    sizeSchema: "US",
    lang: "en-US",
    [facetKey]: facetValue
};

如果 facetKey 可以未定義,您可以這樣做。

let params = {
    store: "US",
    offset: props.offset,
    categoryId: props.categoryId,
    limit: props.limit,
    country: "US",
    sort: "freshness",
    currency: "USD",
    sizeSchema: "US",
    lang: "en-US",
};

facetKey && params = { ...params, [facetKey]: facetValue }
// or
if (facetKey) {
    params = { ...params, [facetKey]: facetValue }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM