2017-01-12 17 views
0

componentWillReceivePropsイベントをコンポーネントに登録しました。 the docsで説明されているように、ライフサイクルの更新段階で、このイベントのnextPropsを待ち受けます。componentWillReceivePropsイベントで未定義のnextPropsを解決するにはどうすればよいですか?

しかしnextPropsの値をログに記録することはundefinedを返します - "Chart.js?5478:88 Uncaught TypeError: Cannot read property 'dashboards' of undefined"

私はthis.props.dashboardsの値を割り当てた場合、私は、データが存在していることがわかります。しかし値は最新ではありません。だから私はnextProps.dashboardsを聞いている。

質問:

はなぜcomponentWillReceivePropsでnextPropsパラメータはundefinedを返すのですか?

これは私がダッシュボードとcurrentDashboardの小道具の更新を聞くところファイルChart.jsの要旨です:

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

答えて

4

あなたが実際にnextProps.nextPropsにアクセスしようとしているので、あなたは未定義である、nextPropsを構造化代入されています。非構造がES6でどのように動作するかの詳細については

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. 

    } 

、あなたは大丈夫ああhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

+0

を読むことができますので、代わりに私がnextPropsのアレイ内から小道具名を参照。クール –

関連する問題