Reactjs prop在渲染中可用,但在componentDidMount中不可用

fre*_*rix 4 javascript reactjs

我有一个奇怪的问题.当我从这个类中调用"UserShowStatsSuggestions"时:

var UserShowStatsPanelBody = React.createClass({
    getInitialState: function() {
        return {data: []};
    },
    componentDidMount: function() {
        // Get the show
        var showUrl = "/api/v1/show/" + this.props.showStats.show + "/";
        $.ajax({
            url: showUrl,
            dataType: 'json',
            success: function(data) {
                this.setState({data: data});
            }.bind(this),
            error: function(xhr, status, err) {
                console.error(this.props.url, status, err.toString());
            }.bind(this)
        });
    },
    render: function() {
        var statElements = [];
        // Create the user show stats
        if (this.props.showStats) {
            var showID = this.state.data.id;
            var showLink = "/leaderboards/show/" + showID + "/";
            var recapLink = "/recap/" + this.state.data.id + "/";
            statElements.push(<div className="row"></div>);
            statElements.push(<div className="row"></div>);
            statElements.push(<div className="row"></div>);
            statElements.push(<UserShowStatsSuggestions userID={this.props.userID} showID={showID} />);
            statElements.push(<div className="row"></div>);
        }

        return (
            <div>{statElements}</div>
        );
    }
});
Run Code Online (Sandbox Code Playgroud)

我可以在渲染中访问prop"showID",但不能在componentDidMount中访问:

var UserShowStatsSuggestions = React.createClass({
    getInitialState: function() {
        return {data: []};
    },
    componentDidMount: function() {
        console.log(this.props);
    },
    render: function() {
        console.log(this.props);
        return (
            <div></div>
        );
    }
});
Run Code Online (Sandbox Code Playgroud)

来自componentDidMount console.log:

{userID: "107050829081899378766", showID: undefined}
Run Code Online (Sandbox Code Playgroud)

来自render console.log

{userID: "107050829081899378766", showID: 5705241014042624}
Run Code Online (Sandbox Code Playgroud)

任何想法为什么会这样?

Sil*_*rom 6

查看渲染中的console.log是否多次执行.

componentDidMount只运行一次,因此您永远不会在componentDidMount中看到使用正确的showID执行的另一个console.log.

但是,渲染运行不止一次,因此在父状态更新后,您将看到console.log,其中showId不再为null.

修改父级渲染方法,以便在完成ajax调用之前不渲染.