【问题标题】:How to update state of nested object by id with input select method?如何使用输入选择方法通过 id 更新嵌套对象的状态?
【发布时间】:2019-08-12 08:34:43
【问题描述】:

需要使用自定义键(索引或产品 ID)更新购物车状态

state = {
cart:[
      0:{
        "productID": 1234,
        "size",''
        "color":'',
        "price":1599
      },
  1:{
        "productID": 1162,
        "size",''
        "color":'',
        "price":2899
      },
};

当客户选择颜色购物车项目的值需要更新时

handleChange = input => e => {
    this.setState({ [input]: e.target.value });
  };
render(){
 <NativeSelect
  input={<Input name="color" />}
  // cart[item.productId]
  onChange={handleChange(this.state.cart[0].color)}
  >      
 <option value="">---</option>
 <option value="red">red</option>
 <option value="green">green</option>        

 </NativeSelect>

}

我只需要语法或方法如何将我的商品指向购物车并更新状态

【问题讨论】:

  • 嗨,Djordje,请尝试下面的解决方案,如果有帮助,请告诉我。

标签: reactjs input


【解决方案1】:

您的onChange 处理程序需要知道要更新的产品。所以定义一个函数,将selected 颜色和匹配的productID 作为参数。

查看工作沙箱:https://codesandbox.io/s/determined-hellman-6l20c

工作代码:

import React from "react";
import ReactDOM from "react-dom";
import { NativeSelect, Input } from "@material-ui/core";

import "./styles.css";

class App extends React.Component {
  state = {
    cart: [
      {
        productID: 1234,
        size: "",
        color: "",
        price: 1599
      },
      {
        productID: 1162,
        size: "",
        color: "",
        price: 2899
      }
    ]
  };

  handleOnChange = (e, id) => {
    const cartCopy = JSON.parse(JSON.stringify(this.state.cart));

    let productToUpdate = cartCopy.find(product => product.productID === id);

    productToUpdate.color = e.target.value;

    this.setState(
      {
        cart: cartCopy
      },
      () => console.log(this.state.cart)
    );
  };

  renderCartSelection = () => {
    const { cart } = this.state;

    return cart.map(product => {
      return (
        <div>
          {product.productID}:{" "}
          <NativeSelect
            onChange={e => this.handleOnChange(e, product.productID)}
          >
            <option value="">---</option>
            <option value="red">red</option>
            <option value="green">green</option>
          </NativeSelect>
        </div>
      );
    });
  };

  render() {
    return <div>{this.renderCartSelection()}</div>;
  }
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

【讨论】:

    【解决方案2】:

    如果你在你的 handleChange 中获取并改变整个 state.cart 对象,它可能会更容易找出发生了什么

    handleChange = input => e => {
        const newState = {...this.state.cart}
        newState[0].color = e.target.value
        console.log(newState)
        this.setState(newState);
      };
    

    【讨论】:

      猜你喜欢
      • 2021-12-26
      • 2017-09-30
      • 2018-11-08
      • 2021-04-30
      • 1970-01-01
      • 2018-07-13
      • 2020-05-22
      • 2020-04-27
      • 1970-01-01
      相关资源
      最近更新 更多