当父级中的setState()时,子中的componentWillReceiveProps不会收到新的道具

时间:2017-05-15 09:57:57

标签: javascript reactjs

我在React中有一个名为" App"这会产生一种卡路里"卡路里"具有HighCharts实现的子组件。

我期望的是根据React生命周期,父渲染子组件然后将调用componentDidMount()。然后我使用fetch来获取数据异步,一旦完成它,setState就是带有用户对象的父级。然后它将使用user = {this.state.user}重新呈现子组件,并且它将在子组件中可用。但是当我在子的componentWillReceiveProps中记录this.props时,用户对象并不存在。因此子组件日志中的这一行" undefined":

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>
        );
   }
});

任何人都可以帮助我做错了什么?

1 个答案:

答案 0 :(得分:3)

componentWillReceiveProps child(内部组件内部)的值更新时,

props被调用,您需要在此lifecycle方法中接收新值作为参数,如下所示:

componentWillReceiveProps: function(newProps){ //here
    console.log("component Will Receive Props", newProps); //it will log the new values
    ...
}
this.props内的componentWillReceiveProps将具有以前的值,并且会在此lifecycle方法后更新。如果您在console.log(this.props)render,则会看到更新后的值。

  

为什么我们需要接收新值作为参数?

我认为原因是(不确定),只要我们在父组件中执行setState,就会调用此方法,无论是否与子组件相关,因此我们需要先做一些逻辑孩子的任务(新道具和旧道具是否相同),因为this.props将在此方法中包含旧值。

查看DOC以获取有关componentWillReceiveProps

的更多详细信息