简体   繁体   中英

Can't convert undefined to object (object.keys() function)

I am trying to iterate through the redux store and render all objects present. In an attempt to create an array of the objects I encounter the following error

在此处输入图片说明

The relevant code snippet:

class VictoryChartComp extends React.Component{
constructor(props) {
  super(props);
  //this.ChartsArray = [];
  this.ChartsArray = Object.keys(this.props.newcharts).map(function (key) {
    if (this.props.newcharts.type == 'victory') {
    var item = this.props.newcharts[key];
    return item;
  }
}); 
}

The whole code can be found here: https://codesandbox.io/s/xr5wk9v35o

I have also tried to declare 'this.ChartsArray' (commented line) but the problem still exists.

Any help would be greatly appreciated.

I tested this out on your sandbox and the fix for the error is of course to validate that this.props.newcharts is not null or undefined . From VictoryChartComp.js

this.ChartsArray = this.props.newcharts
  ? Object.keys(this.props.newcharts).map(function(key) {
    if (this.props.newcharts.type === "victory") {
      var item = this.props.newcharts[key];
        return item;
      }
    })
  : [];

This will allow ChartsArray to not be undefined if this.props.newCharts is null .

Even though this solves the console error and allows the component to render it comes out blank - because newCharts is undefined in my execution. I'm not sure if that is what you actually want. You might want to make newCharts required.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM