Ad

React Component Not Setting State

- 1 answer

I have a React component to represent a task list, called <Tasks> that looks like this:

var Tasks = React.createClass({
    getInitialState: function () {
        return {
            tasks: []
        };
    },
    componentDidMount: function () {
        this.setState({
            tasks: this.props.tasks
        });
    },
    render: function () {
        var tasks = this.state.tasks.map(function (task) {
            return (
                <Task key={task.id} description={task.description} completed={task.completed} />
            );
        });
        return (
            <table className="table table-tasks">
                <tbody>
                    {tasks}
                </tbody>
            </table>
        );
    }
});

But this.state.tasks is not being set. Using the React inspector for Chrome, I can see this.props.tasks is an array of two objects (expected), but this.state.tasks is an empty array. So it seems the setState call in my componentDidMount method isn’t actually setting the state.

What am I doing wrong?

Ad

Answer

Turns out I can access props in getInitialState(). No idea where I’ve picked up the convention of setting state in componentDidUpdate(), so now I’m just doing:

var Tasks = React.createClass({
    getInitialState: function () {
        this.setState({
            tasks: this.props.tasks
        });
    },
    render: function () {
        var tasks = this.state.tasks.map(function (task) {
            return (
                <Task key={task.id} description={task.description} completed={task.completed} />
            );
        });
        return (
            <table className="table table-tasks">
                <tbody>
                    {tasks}
                </tbody>
            </table>
        );
    }
});

Thanks to Jack Franklin for the tip!

Ad
source: stackoverflow.com
Ad