@MrChen

Как постоянно обновлять данные при помощи componentDidMount?

Всем привет! У меня есть файл app.js:

import React from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';
import {Articles} from './articles';

class Form extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            articles: {},

            messages: {
                error: '',
                success: false
            }
        };

        this.handleChangeForm = this.handleChangeForm.bind(this);
        this.handleSubmitForm = this.handleSubmitForm.bind(this);
    }

    handleChangeForm(event) {
        let name = event.target.name;
        let articles = Object.assign({}, this.state.articles);
        articles[name] = event.target.value;
        this.setState({articles});
    }

    handleSubmitForm(event) {
        event.preventDefault();

        axios.post('/articles/add', {
            title: this.state.articles.title,
            content: this.state.articles.content
        })
            .then(function(response) {
                this.setState({
                    messages: {
                        success: true
                    }
                });
            }.bind(this))
            .catch(function(error) {
                this.setState({
                    messages: {
                        error: error
                    }
                }.bind(this));
            });
    }

    render() {
        return (
            <div>
                <form onChange={this.handleChangeForm} onSubmit={this.handleSubmitForm}>
                    {this.state.messages.success && (
                        <div>
                            Статья успешно добавлена
                        </div>
                    )}

                    {this.state.messages.error && (
                        <div>
                            Произошла ошибка при добавлении: {this.state.messages.error}
                        </div>
                    )}

                    <input type="text" placeholder="title" name="title"/> <br/>
                    <input type="text" placeholder="content" name="content"/> <br/>

                    <input type="submit" value="Добавить статью"/>
                </form>

                <Articles />
            </div>
        )
    }
}

ReactDOM.render(<Form />, document.getElementById('app'));


И есть файл articles.jsx, который экспортится в app.jsx:

import React from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';

export class Articles extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            articles: []
        }
    }

    componentDidMount() {
        axios.get('/articles/get')
            .then(function (response) {
                const articles = response.data;
                this.setState({articles});
            }.bind(this))
            .catch(function (error) {
                console.log(error);
            });
    }

    render() {
            const articles = this.state.articles.map(art =>
                (
                    <article key={art.id}>
                        <h1>{art.title}</h1>

                        <p>{art.content}</p>

                        <button>Удалить</button>
                    </article>
                )
            );


        return <div>{articles}</div>;
    }
}


Проблема, собственно, в том, что когда я нажимаю на Submit, componentDidMount не срабатывает... Как с этим бороться?
  • Вопрос задан
  • 494 просмотра
Пригласить эксперта
Ответы на вопрос 2
Hardwit
@Hardwit
Front-end Developer
componentDidMount и не должен срабатывать. Запиши в стейте родительского компонента какое-нибудь свойство и прокинь его в свой компонент Articles. Изменяй этот свойство в родителе по успешному сабмиту формы. В дочернем компоненте используй componentWillRecieveProps docs и по изменению этого свойства дергай свой аякс.
Ответ написан
maxfarseer
@maxfarseer
https://maxpfrontend.ru, обучаю реакту и компании
componentDidMount = "компонент примонтирован". То есть он будет примонтирован еще раз, только если он будет до этого размонтирован, а для этого вам нужно его выкинуть из текущей верстки.

Рекомендую использовать в вашем случае componentdidupdate (разобраться что это за "лайфхук").
Ответ написан
Комментировать
Ваш ответ на вопрос

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

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