简体   繁体   中英

react-table adds reference on row click

I'm currently facing the following issue: I'm working on a react web app which contains one component that displays products that are contained in the products array state. A product can be added by clicking on a table row of a react-table which contains different products. A product can be added multiple times by clicking on the same product.

getTdProps={(state, rowInfo, column, instance) => {
              return {
                onClick: (e, handleOriginal) => {
                  that.props.handleProductSelect(rowInfo.original);
                }
              };
            }}

If a table row is clicked, the handleProductSelect function is called which passes the original data as parameter.

handleProductSelect(oSelProduct) {
    oSelProduct["amount"] = 1;
    oSelProduct["selectedVariantOptions"] = [];
    this.setState(
      prevStates => ({
        products: [...prevStates.products, oSelProduct]
      }),
      () => {
        ...
      }
    );
  }

The selected product will be added to the products array, the component will be re-rendered and the products will be shown in a standard html table.

Each rendered product contains a plus and minus button to change the amount of each product. The plus button eg calls the handlePlusButton function:

handlePlusButton(i) {
    this.setState(state => {
      const products = state.products.map((product, j) => {
        if (j === i) {
          product.amount = product.amount + 1;
          return product;
        } else {
          return product;
        }
      });
      return {
        products
      };
    });
  }

Problem: If I click on the same product multiple times, they will be added to the product array. Now if I click on the plus button to change the amount, somehow the amount will be changed for all products which where added. So somehow it looks like a reference is added to the products array. How can I avoid this behaviour?

The problem happens, becuase You are adding two references to the same product. Try to change handleProductSelect to this:

handleProductSelect(oSelProduct) {
    const newProduct = {
       ...oSelProduct,
       amount: 1,
       selectedVariantOptions: []
    };

    this.setState(
      prevStates => ({
        products: [...prevStates.products, newProduct]
      }),
      () => {
        ...
      }
    );
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM