如何解决 componentWillReceiveProps 事件中未定义的 nextProps?

How to resolve undefined nextProps in componentWillReceiveProps event?

我已经在组件中注册了 componentWillReceiveProps 事件。如 the docs 中所述,我在生命周期的更新阶段在此事件中监听 nextProps。

但是记录 nextProps 的值 returns 未定义 - "Chart.js?5478:88 Uncaught TypeError: Cannot read property 'dashboards' of undefined"

如果我分配 this.props.dashboards 的值,我可以看到数据存在。但是这些值不是最新的。这就是为什么我听 nextProps.dashboards.

问题:

为什么 componentWillReceiveProps return 中的 nextProps 参数未定义?

这是 Chart.js 文件的要点,我在其中侦听仪表板和 currentDashboard 道具的更新:

import React, { Component } from 'react';
import { connect } from 'react-redux';    
import Spinning from 'grommet/components/icons/Spinning';
import Heading from 'grommet/components/Heading';
import drawing from '../chartLib/';



 class Chart extends Component {
    constructor (props) {
        super(props);
        this.state = {data: [], loading: true};
    }


    componentWillReceiveProps ({ blockName, subcatName, nextProps }) {

        if(nextProps.dashboards)  //this check for nextProps.dashboards returns: "Chart.js?5478:88 Uncaught TypeError: Cannot read property 'dashboards' of undefined"
        {
            console.log("The nextprops dashboards values are: " + nextProps);

        }

         this.setState({ loading: true});
         var dashboardsArray = this.props.dashboards;     //this contains the dashboards property value, but the values are one less than the last update.

    }

    render() {
        if (this.state.loading) {
            return <Spinning />;
        } else {
            if (this.state.data.length === 0) { 
                return (<Heading>Nothing to Show</Heading>);
            } else {
                return (
                    <div className={'why'}>
                        {drawing(this.state.data)[this.props.blockName][this.props.subcatName]}
                    </div>
                );
            }
        }
    }
}


Chart.propTypes = {
  blockName: React.PropTypes.string.isRequired,
  subcatName: React.PropTypes.string.isRequired,
  currentDashboard: React.PropTypes.string.isRequired,
  dashboards : React.PropTypes.array.isRequired
};



const mapStatetoProps = ({ currentDashboard, dashboards }) => ({ currentDashboard, dashboards });

您正在解构 nextProps,所以您实际上是在尝试访问未定义的 nextProps.nextProps

componentWillReceiveProps ({ blockName, subcatName, dashboards }) {

        if(dashboards)  
        {
            console.log("The nextprops dashboards values are: " + dashboards);

        }

         this.setState({ loading: true});
         var dashboardsArray = this.props.dashboards;     //this contains the dashboards property value, but the values are one less than the last update.

    }

有关解构在 ES6 中如何工作的更多信息,您可以阅读 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment