Ожидаемый эффект: нажмите кнопку -> вызвать функцию add
-> добавить объект this.color
в массив products
- свойство colors
в компоненте App. Пример:
colors: [{color:" green "}, {color:" black "}]
-> colors: [{color: "green"}, {color: "black"}, {color: "red "}]
Ошибка: Ошибка типа: невозможно прочитать свойство «push» из неопределенного
App
class App extends React.Component {
state = {
products: [
{ id: 0, colors: [{color:"green"}, {color:"black"}], desc: "some desc" },
{ id: 1, colors: [{color:"yellow"}, {color:"purple"}], desc: "some desc1" }
],
index: null
};
add = (newColor) => {
let newProducts = [...this.state.products]
newProducts[index].colors.push(newColor);
this.setState({products: newProducts});
}
select = (index) => {
this.setState({
index: index
})
}
render() {
<div>
<ul>
{
this.state.products.map((product, index) => (
<Product
key={product.id}
product={product}
select={() => this.select(index)}
/>
))
}
</ul>
<Details
add={this.add}
/>
</div>
}
}
Детали
class Details extends React.Component {
click1 = () => {
this.color = {
color: 'red'
}
this.props.add(this.color);
}
render() {
<div>
<button onClick={this.click1}></button>
</div>
}
}