簡體   English   中英

當父級中的setState()時,子級中的componentWillReceiveProps不會收到新的道具

[英]componentWillReceiveProps in child doesn't receive new props when setState() in parent

我在React中有一個名為“App”的父組件,它使用HighCharts實現呈現“Calories”子組件。

我期望的是根據React生命周期,父渲染子組件然后將調用componentDidMount()。 然后我使用fetch來獲取數據異步,一旦完成它就使用了用戶對象的setState。 然后它將使用user = {this.state.user}重新呈現子組件,並且它將在子組件中可用。 但是當我在子的componentWillReceiveProps中記錄this.props時,用戶對象不存在。 所以子組件中的這一行記錄為“未定義”:

componentWillReceiveProps: function(){
    const series = this.props.series;

    console.log("component Will Receive Props")
    console.log(this.props);
}

這是我的完整代碼:

const App = React.createClass({
//parent component to render all elements and hold state
    getInitialState(){
        return{
            user: {},
            series: [{
                name: 'Jane',
                data: [1, 0, 4]
             }, {
                name: 'John',
                data: [5, 7, 3]
            }]
        };
    },

    componentDidMount: function(){

      const fb_id = location.pathname.replace("/users/","");

      fetch("https://someurl.com/usersdata/" + fb_id)
        .then(rsp => rsp.json())
        .then(json => {
            if(json.error && json.error.message){
                throw new Error(json.error.message);
            } 
            this.setState({user:json}, ()=>{
                console.log("state updated");
                console.log(this.state);
            });
        });

    },

    render: function(){
        return (
            <div className="container">
                <div clasNames="row">
                    <div className="col-xs-12">
                         {/*Send this.state.user data from fetch to child component*/}
                         <Calories series={this.state.series} user={this.state.user}/>
                    </div>
                </div>
                <div className="row">
                    <div className="col-xs-7">
                        <div className="bottom-left" id="weight-line-chart">
                            <Weight/>
                         </div>
                    </div>
                    <div className="col-xs-5">
                        <div className="bottom-right" id="avg-calories-pie-chart">
                            <AverageCal/>
                        </div>
                    </div>
                </div>
        </div>
        );
    }

});

//Calories Line chart
const Calories = React.createClass({

    componentDidMount: function(){

        const series = this.props.series;

        console.log("component Did Mount");
        console.log(this.props);

        $(function () { 
            const myChart = Highcharts.chart('calories-line-chart', {
            chart: {
                type: 'line'
            },
            title: {
                text: 'Your Calories Over Time'
            },
            xAxis: {
                categories: ['Apples', 'Bananas', 'Oranges']
            },
            yAxis: {
                title: {
                    text: 'Fruit eaten'
                }
            },
            series: series
            });
        });

    },

    componentWillReceiveProps: function(){

        const series = this.props.series;

        console.log("component Will Receive Props")
        console.log(this.props);

        $(function () { 
            const myChart = Highcharts.chart('calories-line-chart', {
            chart: {
                type: 'line'
            },
            title: {
                text: 'Your Calories Over Time'
            },
            xAxis: {
                categories: ['Apples', 'Bananas', 'Oranges']
            },
            yAxis: {
                title: {
                    text: 'Fruit eaten'
                }
            },
            series: series
            });
        });

    },

   render:function(){
       return(
            <div>
                <h3>Calories Intake</h3>
                <div className="top" id="calories-line-chart">

                </div>
           </div>
        );
   }
});

任何人都可以幫助我,我做錯了什么?

componentWillReceiveProps被調用時props子(父組件內)的值將得到更新,您需要接受新的值作為該參數lifecycle方法,就像這樣:

componentWillReceiveProps: function(newProps){ //here
    console.log("component Will Receive Props", newProps); //it will log the new values
    ...
}

this.propscomponentWillReceiveProps將有之前的值,它會在這之后得到更新lifecycle方法。 如果在render執行console.log(this.props) ,您將看到更新的值。

為什么我們需要接收新值作為參數?

我認為原因是(不確定),每當我們在父組件中執行setState時都會調用此方法,無論是否與子組件相關,因此我們需要在對子進行任何任務之前設置一些邏輯(新的道具和舊道具是否相同),因為this.props將在此方法中具有舊值。

有關componentWillReceiveProps更多詳細信息,請查看DOC

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM