【问题标题】:Manipulating an array without overriding elements在不覆盖元素的情况下操作数组
【发布时间】:2020-08-09 20:28:13
【问题描述】:

我正在尝试制作一个价格数组,它的逻辑包含在这个函数中

function getPrices(qty: number, id: string) {
    let mappedPrices = inCart.map(item => item.price)
    let product = inCart.find(item => item.id === id)

    const itemIndex = mappedPrices.indexOf(product.price)
    const newPrice = qty * product.price

    if (~itemIndex) {
        mappedPrices[itemIndex] = newPrice   
    } else {
      mappedPrices
    }

    console.log(mappedPrices)
  }


//inCart types -- [{name: string, image: string, price: number, id: string}]

//Example = [{name: 'shoe', image: 'shoe.png', price: 30, id: 'shoeid'}]

每次我控制台记录它时,都会对一个数字进行更改,但另一个会返回到它的初始值。关于如何解决它的任何线索?

每个 cartItem 组件都会调用 getPrice 函数


 useEffect(() => {
    getPrices(qty, data.id)
  }, [qty])

【问题讨论】:

  • 请添加一些数据例如
  • mappedPrice 只包含价格,所以mappedPrices.indexOf(product.price) 是一个非常糟糕的主意,以防有两种价格相同的产品。
  • 你完全正确,但我想不出其他解决方案

标签: javascript arrays reactjs typescript


【解决方案1】:

你正在这样做:

let mappedPrices = inCart.map(item => item.price)

也就是说你的mappedPrices是基于inCart的默认价格,所以每次调用getPrices()只会改变对应产品的价格。

要么使用 foreach 对您的 inCart 产品一次获取所有价格,要么执行 getPrice()(单数)方法并且只获取一个价格。

当然,您将根据自己处理购物车的方式进行选择。

这是a repro on Stackblitz,这是代码:

import React, { Component } from "react";
import { render } from "react-dom";
import "./style.css";

const App = () => {
  const products = [
    {name: 'shoe', image: 'shoe.png', price: 30, id: 1},
    {name: 'boots', image: 'boots.png', price: 25, id: 2}
  ];

  React.useEffect(() => {
    const prices = products.map(p => getPrice(5, p.id))
    console.log(prices);
  });

  const getPrice = (qty, id) => {
    const product = products.find(item => item.id === id)
    const newPrice = qty * product.price

    return newPrice;
  }

  return (
    <div>
      This is a template react
    </div>
  );
};

render(<App />, document.getElementById("root"));

这里没有覆盖任何内容,您只需根据其数据计算当前产品的新价格。

【讨论】:

  • 你编辑了什么?我知道你的需求是什么,我给你举了例子,我会用一个例子来编辑给你看:)
  • 不客气 :) 如果这是您要寻找的,请不要将答案标记为已接受和/或赞成 :) 告诉我您是否需要从此代码中获得更多信息
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-05-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-11
  • 1970-01-01
  • 2012-12-14
相关资源
最近更新 更多