繁体   English   中英

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

[英]Reactjs prop available in render but not in componentDidMount

我有一个奇怪的问题。 当我从这个类中调用“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>
        );
    }
});

我可以在渲染中访问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>
        );
    }
});

来自componentDidMount console.log

{userID: "107050829081899378766", showID: undefined}

来自render console.log

{userID: "107050829081899378766", showID: 5705241014042624}

任何想法为什么会这样?

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM