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

2023-12-23

我在 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.props inside componentWillReceiveProps将具有以前的值,并将在此之后更新lifecycle方法。如果你这样做console.log(this.props) inside render,您将看到更新后的值。

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

我认为原因是(不确定),每当我们这样做时都会调用这个方法setState在父组件中,无论是否与子组件相关,因此我们需要在子组件中执行任何任务之前放置一些逻辑(新道具和旧道具是否相同),因为this.props此方法内将具有旧值。

检查DOC https://facebook.github.io/react/docs/react-component.html#componentwillreceiveprops欲了解更多详细信息componentWillReceiveProps.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

当父级中的 setState() 时,子级中的 componentWillReceiveProps 不会收到新的 props 的相关文章

随机推荐