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

时间:2017-01-12 11:05:08

标签: javascript reactjs react-redux

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

但是记录nextProps的值会返回undefined - "Chart.js?5478:88 Uncaught TypeError: Cannot read property 'dashboards' of undefined"

如果我指定this.props.dashboards的值,我可以看到数据存在。但价值观并不是最新的。这就是为什么我会听nextProps.dashboards

问题:

为什么componentWillReceiveProps中的nextProps参数返回undefined?

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

1 个答案:

答案 0 :(得分:5)

您正在解构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