@ThomasScott

Где ошибки в коде?

class MyComponent extends React.component {
    constructor() {
        this.state = {
            counter: 0,
            items: [1, 2]
        };
    }

    increase(this) {
        this.state.counter++;
    }

    addItem() {
        this.state.items = this.state.items.push(this.state.items.length+1);
    }

    render() {
        <div class="data">
            <div>{this.state.counter}</div>
            <ul>
            {this.state.items.map(item => (
                <li key={item}>element {item}</li>
            ))}
            </ul>
        </div>
        <div class="actions">
            <button type="button" onclick={this.increase}>zwiększ</button>
            <button type="button" onclick={this.addItem}>dodaj</button>
        </div>
    }
}

ReactDOM.render(<MyComponent>, document.querySelector("body"));
  • Вопрос задан
  • 91 просмотр
Решения вопроса 2
здесь:

constructor() {
        this.state = {
            counter: 0,
            items: [1, 2]
        };
    }

    increase(this) {
        this.state.counter++;
    }

    addItem() {
        this.state.items = this.state.items.push(this.state.items.length+1);
    }


Там где конструктор нужен super(props);
Ответ написан
Комментировать
@Narts
this.state.counter++;
Так делать нельзя, как и
this.state.items = this.state.items.push(this.state.items.length+1);

Вы уходите от одной из основных реакт концепций - иммутабельности.

Правильно делать так:
this.setState({counter: this.state.counter+1});
и
this.setState({items: ...this.state.items, this.state.items.length+1});

или через concat

Так же верно подметили на счет super(props);
Вы используете классовые компоненты и надо вызывать конструктор родительского класса
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы