【问题标题】:How to update multiple state in react js如何在反应js中更新多个状态
【发布时间】:2020-09-23 03:43:32
【问题描述】:

我不确定问题的标题是否正确。我遇到了一些问题,我不知道如何解决。

在我的应用中有购物车页面,里面有商品列表。每个项目都有一个字段数量。可以更新。我的问题是当我启动 i 状态数量并从中创建两个函数来增加和减少数量时。但问题是当我单击 addQuantity 时,它会同时更新所有产品数量。我真的不知道要解决这个问题,我从过去几天一直试图弄清楚。 这是两个项目。

这些是我的代码

类 CartContainer 扩展 React.Component { 状态 = { 数量:1, };

componentDidMount() { this.props.getItemsAddedToCart(); }

渲染() {

const addItem = () => {
  this.setState({
    quantity: this.state.quantity + 1,
  });
};

const removeItem = () => {
  this.setState({
    quantity: this.state.quantity - 1,
  });
};

购物车.js

return cartData.map((item, index) => { 返回 (

      <Grid item xs={4} container justify="space-around">
        <CartItemDetails
          quantity={quantity}
          addItem={addItem}
          removeItem={removeItem}
          addQty={addQuantity}
          subQty={subtractQuantity}
          cart={item}
        />
      </Grid>
    </Grid>
  </Grid>
);

CartItemDetail.js

return (
  <Grid container className="cart-item-details">

    <Grid xs={12} md={4}>
      {!this.props.team ? (
        <Grid className="counter" xs={12} container>
          <Grid container justify="center" alignItems="center" xs={4}>
            <button
              onClick={this.props.removeItem}
              className="decrement"
            ></button>
          </Grid>
          <Grid container justify="center" alignItems="center" xs={4}>
            <span>{this.props.quantity}</span>
          </Grid>
          <Grid container justify="center" alignItems="center" xs={4}>

            <button
              onClick={this.props.addItem}
              className="increment"
            ></button>
          </Grid>
        </Grid>
      ) : (
        ""
      )}

任何帮助都会很棒,我真的很想弄清楚这一点。

【问题讨论】:

  • 你能创建一个 CodeSandbox 让我们使用一个工作示例吗?
  • 是的,给我一分钟,我会尽力的。
  • @Titulum 这是一个很大的应用程序,我无法将它添加到沙盒中
  • 您不应该将您的完整应用添加到 CodeSandbox,这只是一个可以让我们重现您的问题的小型工作示例。

标签: javascript reactjs


【解决方案1】:

您只为您的状态中的数量保留一个值,因此 Cart.js 呈现的所有购物车商品都使用相同的值。

您需要跟踪购物车中每件商品的数量,以下是为每件商品设置状态的示例:

this.state = {
      items: [
        {
          id: 1,
          name: "Jeans",
          quantity: 1
        },
        {
          id: 2,
          name: "Jacket",
          quantity: 2
        }
      ]
    };

以及增加和减少项目的功能

increaseItemQuantity(id) {
    return () => {
      const itemIndex = this.state.items.findIndex(item => item.id === id);
      const nextItems = Array.from(this.state.items);
      console.log(itemIndex);
      nextItems[itemIndex].quantity = nextItems[itemIndex].quantity + 1;
      this.setState([...nextItems]);
    };
  }

  decreaseItemQuantity(id) {
    return () => {
      const itemIndex = this.state.items.findIndex(item => item.id === id);
      const nextItems = Array.from(this.state.items);
      console.log(itemIndex);
      nextItems[itemIndex].quantity = Math.max(
        1,
        nextItems[itemIndex].quantity - 1
      );
      this.setState([...nextItems]);
    };
  }

(这可以做得更干净,但为了演示目的,我将保持原样)

然后在渲染中:

render() {
    return (
      <div className="App">
        <div>
          {this.state.items.map((item, index) => (
            <div key={item.id}>
              {item.name} x{item.quantity}
              <br />
              <button
                type="button"
                onClick={this.decreaseItemQuantity(item.id)}
              >
                Decrease
              </button>
              <button
                type="button"
                onClick={this.increaseItemQuantity(item.id)}
              >
                Increase
              </button>
              <br />
              <br />
            </div>
          ))}
        </div>
      </div>
    );
  }

在这里试试:https://codesandbox.io/s/solitary-dawn-8gpjl?file=/src/App.js

【讨论】:

  • 我将如何处理 redux 状态?
【解决方案2】:

像下面这样声明你的状态

state={
quantity:{}
}

使用产品ID或独特的东西来制作数量的关键

const addItem = (id) => {
  this.setState({
    quantity: {
     ...this.state.quantity,
     [id]:this.state.quantity[id]+1
     }
  });
};

const removeItem = (id) => {
  this.setState({
    quantity: {
     ...this.state.quantity,
     [id]:this.state.quantity[id]-1
     }
  });
};
      <Grid item xs={4} container justify="space-around">
        <CartItemDetails
          quantity={this.state.quantity[id]||0}
          addItem={addItem}
          removeItem={removeItem}
          addQty={addQuantity}
          subQty={subtractQuantity}
          cart={item}
        />
      </Grid>
    </Grid>
  </Grid>
);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-26
    • 1970-01-01
    • 2022-01-16
    • 2018-10-22
    • 1970-01-01
    • 2020-10-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多