M
M
MrChen2017-08-17 15:21:29
JavaScript
MrChen, 2017-08-17 15:21:29

How to keep updating data with componentDidMount?

Hello! I have app.js file:

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'));

And there is an articles.jsx file that will be exported to 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>;
    }
}

The problem is that when I click Submit, componentDidMount doesn't work... How can I deal with this?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ivan Minakov, 2017-08-17
@Hardwit

componentDidMount and shouldn't fire. Write some property in the state of the parent component and pass it to your Articles component. Change this property in the parent on successful form submission. In the child component, use the componentWillRecieveProps docs and change this property, pull your ajax.

M
Maxim, 2017-08-17
@maxfarseer

componentDidMount = "component is mounted". That is, it will be mounted again only if it has been unmounted before, and for this you need to throw it out of the current layout.
I recommend using componentdidupdate in your case (figure out what kind of "lifehook" it is).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question