import React, {Component} from "react";
import InnerComponent from "./InnerComponent";
import ItemComponent from "./ItemComponent";
class MyContainer extends Component {
state = {
items: [{name: "item1", price: 1.1, key: 1},
{name: "item2", price: 2.1, key: 2},
{name: "item3", price: 3.1, key: 3},
{name: "item4", price: 4.1, key: 4},
{name: "item5", price: 5.1, key: 5}
],
count: 5
};
deleteItem = (index) => {
this.setState((prevState, props) => {
const newItems = [...prevState.items];
newItems.splice(index, 1);
return {
items: newItems
}
});
};
addItems = () => {
this.setState((prevState, props) => {
const newItems = [...prevState.items];
let count = prevState.count + 1;
newItems.push({name: "item" + count, price: count + 0.1, key: count});
return {
items: newItems,
count: count
}
});
};
render() {
const items = this.state.items.map((item, index) => {
return ( this.deleteItem(index)}
/>)
});
return (
{items}
)
}
}
export default MyContainer;
==== Other Than Using map function ====
There are multiple way to do the looping, we can use ''for ... in'' or ''forEach'' to achieve the same result. It is just personal preference to use which.
let items = [];
let index = 0;
for (const item of this.state.items) {
items.push( this.deleteItem(index)}/>)
index++;
}
let items = [];
this.state.items.forEach(function (item, index) {
items.push( this.deleteItem(index)}/>)
});
===== ItemComponent=====
Item component is very simple, we only need to display the info from the ''prop'', and hook up the onClick event.
import React from "react";
const ItemComponent = (prop) => {
return (
name: {prop.name}, price: ${prop.price}, key: {prop.index}
);
};
export default ItemComponent;