简体   繁体   English

将多个对象添加到数组?

[英]Add multiple objects to an array?

Every time I click an option of size and click add to cart I would like to add the data of the selected object to this array cart . 每次单击大小选项并单击添加到购物车时,我想将所选对象的数据添加到此数组cart This currently works kinda but only one object can be added and when you try to do it again the old data disappears and is replaced with the new object. 这目前可以,但是只能添加一个对象,当您尝试再次添加它时,旧数据将消失,并被新对象替换。

I would like to keep odd objects in the array and add new objects too. 我想将奇数对象保留在数组中,并添加新对象。 How do I go about doing this? 我该怎么做呢?

index.js index.js

export class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      evenSelected: null
    };
  }

  handleSelectL1 = i => {
    this.setState({
      evenSelected: i,
      oldSelected: null
    });
  };

  render() {
    const product = [
      {
        name: " size one",
        price: 1
      },
      {
        name: "size two",
        price: 2
      },
      ,
      {
        name: "size three",
        price: 3
      }
    ];

    const cart = [];

    const addCart = function() {
      cart.push(product[evenIndex]);
      if (cart.length > 0) {
      }
    };
    console.log("cart", cart);

    const evenIndex = this.state.evenSelected;
    const priceShown = product[evenIndex] && product[evenIndex].price;
    return (
      <div>
        <Child
          product={product}
          handleSelectL1={this.handleSelectL1}
          evenIndex={evenIndex}
        />
        <h2>Price:{priceShown} </h2>
        <button onClick={addCart}>Add to cart</button>
      </div>
    );
  }
}

child.js child.js

export class Child extends Component {
  constructor(props) {
    super(props);

    this.state = {};
  }

  render() {
    const { product, evenIndex } = this.props;

    return (
      <div>
        {product.map((p, i) => {
          return (
            <div
              key={p.id}
              className={evenIndex === i ? "selectedRBox" : "selectorRBox"}
              onClick={() => this.props.handleSelectL1(i)}
            >
              <h1 className="selectorTextL">{p.name}</h1>
            </div>
          );
        })}
      </div>
    );
  }
}

Here is my code on sandbox: https://codesandbox.io/s/14vyy31nlj 这是我在沙箱上的代码: https : //codesandbox.io/s/14vyy31nlj

I've just modified your code to make it work. 我刚刚修改了您的代码以使其正常工作。 Here is the complete code . 这是完整的代码 You need cart to be part of the state, so it does not initialize in each render, and to make the component render again when you add an element. 您需要cart作为状态的一部分,因此它不会在每个渲染中初始化,并在添加元素时使组件再次渲染。

Remove the function to make it a method of the class: 删除该函数以使其成为该类的方法:

  addToCart() {
    const selectedProduct = products[this.state.evenSelected];
    this.setState({
      cart: [...this.state.cart, selectedProduct]
    });
  }

And call it on render: 并在render上调用它:

  render() {
    console.log("cart", this.state.cart);
    const evenIndex = this.state.evenSelected;
    const priceShown = products[evenIndex] && products[evenIndex].price;
    return (
      <div>
        <Child
          product={products}
          handleSelectL1={this.handleSelectL1}
          evenIndex={evenIndex}
        />
        <h2>Price:{priceShown} </h2>
        <button onClick={this.addToCart.bind(this)}>Add to cart</button>
      </div>
    );
  }
}

Check that I have binded on render, which can bring performance issues in some cases. 检查我是否绑定了渲染,在某些情况下会带来性能问题。 You should check this 你应该检查一下

Update 更新资料

As devserkan made me notice (Thanks!), when you use the previous state to define the new state (for example adding an element to an array), it is better to use the updater function instead of passing the new object to merge: 正如devserkan使我注意到(谢谢!)一样,当您使用以前的状态来定义新状态(例如,将元素添加到数组中)时,最好使用updater函数,而不是传递新对象进行合并:

this.setState(prevState => ({
  cart: [...prevState.cart, products[selectedProduct]],
}));

For more info check the official docs . 有关更多信息, 请查看官方文档

I don't quite understand what are you trying to but with a little change here it is. 我不太了解您要做什么,但是这里有一些更改。 I've moved product out of the components like a static variable. 我已将product从组件中移出,就像静态变量一样。 Also, I've changed the addCart method, set the state there without mutating the original one and keeping the old objects. 另外,我更改了addCart方法,在其中设置状态,而无需更改原始状态并保留旧对象。

 const product = [ { name: " size one", price: 1 }, { name: "size two", price: 2 }, { name: "size three", price: 3 } ]; class App extends React.Component { constructor(props) { super(props); this.state = { evenSelected: null, cart: [], }; } handleSelectL1 = i => { this.setState({ evenSelected: i, oldSelected: null }); }; addCart = () => { const evenIndex = this.state.evenSelected; this.setState( prevState => ({ cart: [ ...prevState.cart, product[evenIndex] ], })) }; render() { console.log(this.state.cart); const evenIndex = this.state.evenSelected; const priceShown = product[evenIndex] && product[evenIndex].price; return ( <div> <Child product={product} handleSelectL1={this.handleSelectL1} evenIndex={evenIndex} /> <h2>Price:{priceShown} </h2> <button onClick={this.addCart}>Add to cart</button> </div> ); } } class Child extends React.Component { constructor(props) { super(props); this.state = {}; } render() { const { product, evenIndex } = this.props; return ( <div> {product.map((p, i) => { return ( <div key={p.id} className={evenIndex === i ? "selectedRBox" : "selectorRBox"} onClick={() => this.props.handleSelectL1(i)} > <h1 className="selectorTextL">{p.name}</h1> </div> ); })} </div> ); } } const rootElement = document.getElementById("root"); ReactDOM.render(<App />, rootElement); 
 .selectorRBox { width: 260px; height: 29.5px; border: 1px solid #727272; margin-top: 18px; } .selectedRBox { width: 254px; height: 29.5px; margin-top: 14px; border: 4px solid pink; } .selectorTextL { font-family: "Shree Devanagari 714"; color: #727272; cursor: pointer; font-size: 18px; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="root"></div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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