首页 文章

React和d3在react组件中导入数据 - 无法读取未定义的属性'length'

提问于
浏览
0

我在我的应用程序中实现了这个chart示例

查看有关如何组成的图像

enter image description here

问题是,如果我的 nums 数据像这样硬编码,我只能正确显示我的图表填充数据 const nums = [32, 19, 47, 38, 17, 62, 94, 21, 59, 62];

export默认类ChartsGrid扩展了React.Component {

render() {

    const view = [480, 320];
    const trbl = [0, 0, 0, 0]
    const horizontalAxisHeight = 30;
    const verticalAxisWidth = 42;
    const nums = [32, 19, 47, 38, 17, 62, 94, 21, 59, 62];

    return (
      <div className="grid">
          <LineChart {...{view, trbl, nums, horizontalAxisHeight, verticalAxisWidth}} />
      </div>
    )
  }
};

如果我在我的 ChartsGrid 组件中将我的数据声明为道具 const { nums } = this.props; ,那么我在 LineChart 组件中出现此错误

TypeError: Cannot read property 'length' of undefined

这是因为它抱怨 LineChart 中的渲染函数中的 nums

const {view, trbl, nums, horizontalAxisHeight, verticalAxisWidth} = this.props;

我的 nums 数据实际上是在商店中可以使用的(我可以在控制台中看到它)

num.js

const nums = [32, 19, 47, 38, 17, 62, 94, 21, 59, 62];

export default nums;

reducer.js

import { combineReducers } from 'redux';
import { routerReducer } from 'react-router-redux';

import nums from './nums';

const rootReducer = combineReducers({nums, routing: routerReducer });

export default rootReducer;

商店

import rootReducer from './reducers/index';
const store = createStore(rootReducer);

export default store;

这是存储数据num.js的逻辑

那么为什么LineChart无法读取它们呢?

1 回答

  • 0

    您可以指定一个空数组以避免此问题,如下所示

    const nums  = this.props.nums || [];
    

    您应该首先检查此属性为何为null或未定义 . 在分配道具的部分中必定存在一些逻辑错误 .

相关问题