2017-01-12 33 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?

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

回答

4

你解構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

+0

啊好了,所以我反而從nextProps的陣列中引用的道具名稱。涼 –

相關問題