2

The example here - https://facebook.github.io/react/tips/initial-ajax.html - is modified below.

this.state.username is "placeholder" on load and is passed to <UserGist />

After AJAX loads this.state.username is changed to "octocat", but...

How come this is not passed down to the <UserGist /> component?

var UserGist = React.createClass({

    getInitialState: function() {
        return {
            username: this.props.username
        };
    },

    render: function() {
        return (
            <div>
                {this.state.username}
            </div>
        );
    }

});

var App = React.createClass({

    getInitialState: function() {
        return {
            username: 'placeholder'
        };
    },

    componentDidMount: function() {
        this.serverRequest = $.get(this.props.source, function (result) {
            var lastGist = result[0];
            this.setState({
                username: lastGist.owner.login
            });
        }.bind(this));
    },

    componentWillUnmount: function() {
        this.serverRequest.abort();
    },

    render: function() {
        return (
            <div>
                <UserGist username={this.state.username} />
            </div>
        );
    }

});

ReactDOM.render(
    <App source="https://api.github.com/users/octocat/gists" />,
    document.getElementById('main')
);
Ed Williams
  • 2,447
  • 3
  • 15
  • 21

2 Answers2

2

You are passing the new username to your child component, but you are not updating your child state.

If you want to update your child state when the component receives new props, you should implement it.

UserGist component.

componentWillReceiveProps: function(nextProps){
       this.setState({username: nextProps.username});
}
QoP
  • 27,388
  • 16
  • 74
  • 74
1

You should access the value via props in your UserGist component as it is getting passed in as a prop:

var UserGist = React.createClass({
  render: function() {
    return (
      <div>
        {this.props.username}
      </div>
    );
  }
});

Which can then be represented as a stateless functional component (if you are using React > 0.14):

function UserGist(props) {
  return <div>{props.username}</div>
}

It's not necessary to convert it into state unless you are going to be doing some sort of mutation to it within the component itself. It's best to try and use props as far as you can and minimise state.

Some further reading:

Community
  • 1
  • 1
ctrlplusb
  • 12,847
  • 6
  • 55
  • 57