首页 > 解决方案 > React & Axios - 为对象动态添加键和值

问题描述

在我的一个小项目上工作并遇到了一个问题。我正在使用“ASOS”API,我需要动态地将键和值添加到查找正确产品所需的参数中。例如选择颜色、尺寸、价格范围等。问题是,我尝试过的所有事情都没有成功。

如何为对象动态添加键和值?

像这样的东西:

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>
  );
};

谢谢!

请记住 ThefacetKeyfacetValue返回字符串值,以及用户是否没有选择“方面”或过滤产品的选项。然后就返回undefined了,当然可以把这个改成null。

标签: javascriptreactjs

解决方案


您可以将[]运算符与对象一起使用。

一般来说:

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;

推荐阅读