index.js

import React, { Component } from 'react'; import {render} from 'react-dom'; import ItemsList from "../src/components/App" const propsValues = { title: "Список смартфонов", items: [ "HTC U Ultra", "iPhone 7", "Google Pixel", "Hawei P9", "Meizu Pro 6", "Asus Zenfone 3" ] }; render(<ItemsList data={propsValues} />, document.getElementById('root')); 

app.js

 import React, { Component } from 'react'; class Item extends React.Component { render() { return <li>{this.props.name}</li>; } } class ItemsList extends React.Component { constructor(props){ super(props); this.state = { items: this.props.data.items}; } render() { return( <div> <h2>{this.props.data.title}</h2> <ul> { this.state.items.map(function(item){ return <Item key={item} name={item} /> }) } </ul> <button onclick={this.appArr}>ok</button> </div>); } } export default ItemsList; 

I am trying to add a new array a through setState, but it does not work

 function appArr() { let a = [1]; this.setState( { items: [...a, this.props.data.items] } ) } 

    1 answer 1

    1. In the reactor, the register matters. Your example does not work, because you have onclick instead of onclick on your button.

    2. After correction, the example works, but not as it should))). appArr function

     const propsValues = { title: "Список смартфонов", items: [ "HTC U Ultra", "iPhone 7", "Google Pixel", "Hawei P9", "Meizu Pro 6", "Asus Zenfone 3" ] }; class Item extends React.Component { render() { return <li>{this.props.name}</li>; } } class ItemsList extends React.Component { constructor(props){ super(props); this.state = { items: this.props.data.items}; } render() { return( <div> <h2>{this.props.data.title}</h2> <ul> { this.state.items.map(function(item){ return <Item key={item} name={item} /> }) } </ul> <button onClick={this.appArr}>ok</button> </div>); } appArr = () => { let items = this.state.items; items.push('a'); this.setState({ items: items }); } } ReactDOM.render(<ItemsList data={propsValues} />, document.getElementById('root')); 
     <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="root"></div>