I
I
Ivan Filatov2017-03-15 10:51:15
JavaScript
Ivan Filatov, 2017-03-15 10:51:15

Why does a React component not work in one case and work in another?

class Contact extends React.Component {
    constructor(props) {
        super(props);
        this.state = { name: props.name, value: props.value };
    }
    render() {
        return <div>
            <p>{this.state.name}: {this.state.value}</p>
        </div>;
    }
}

class ContactList extends React.Component {
    constructor(props) {
        super(props);
        this.state = { contacts: props.contacts };
    }
    render() {
        return <div>
            {
                this.state.contacts.map(function (c) {
                    return <Contact key={c.name.toString()} name={c.name} value={c.value} />
                })
            }
        </div>;
    }
}

function ContactListTwo(props) {
    const contacts = props.contacts.map((c) =>
        <Contact key={c.name.toString()} name={c.name} value={c.value} />
    );
    return (
        <div>
            {contacts}
        </div>
    );
}

class Root extends React.Component {
    constructor(props) {
        super(props);
        this.state = { contacts: [] };
    }
    loadData() {
        var xhr = new XMLHttpRequest();
        xhr.open("get", this.props.apiUrl, true);
        xhr.onload = function () {
            var data = JSON.parse(xhr.responseText);
            this.setState({ contacts: data.contacts });
        }.bind(this);
        xhr.send();
    }
    componentDidMount() {
        this.loadData();
    }
    render() {
        return <div>
            <ContactList contacts={this.state.contacts} />
            <ContactListTwo contacts={this.state.contacts} />
        </div>;
    }
}

ReactDOM.render(
    <Root apiUrl="/api/contacts" />,
    document.getElementById("content")
);

why in one case -ContactList - does not output anything, and there is no error in the console.
and in the second case - ContactListTwo - everything works out, draws.
when the data is static, both components work. when loading with api - only the one that ContactListTwo handles.
can ContactList draw before receiving data? render fires earlier, I don't understand. then why does the other one work?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ivan, 2017-03-15
@LiguidCool

That's right, you need to call setState to re-render the component. Otherwise, when rendering, there is nothing to show yet, and when there is already, then the render is not called.
The second one works accordingly because xnr.onload... setState

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question