首页 > 解决方案 > React 和 D3:无法读取未定义的属性“X”

问题描述

我是 React 的新手,我有一个项目,在将 D3 安装到我的项目并创建此类后,我将使用它来创建我的图表:

import React, { Component } from 'react';
var ReactDOM = require('react-dom');
var LineChart = require('react-d3-basic').LineChart;

class TempChart extends Component{
constructor(){
    super();
    this.state={
        generalChartData:{},
        chartSeries:[],
        x:0
    }
}

componentWillMount(){
    fetch("my JSON url was here")
    .then(response=>response.json())
    .then((findresponse)=>{
        this.setState({
            generalChartData:findresponse.feeds.map((feed, i) => parseFloat(feed.field1)),
            chartSeries:[
              {
                field: 'age',
                name: 'Age',
                color: '#ff7f0e',
                style: {
                  "stroke-width": 2,
                  "stroke-opacity": .2,
                  "fill-opacity": .2
                }
              }
            ],
            x:function(d) {
              return d.index;
            }
        })
    })
}

render(){
    return (
        <LineChart
          width= {600}
          height= {300}
          data= {this.state.generalChartData}
          chartSeries= {this.state.chartSeries}
          x= {this.state.x}
        />
    );
}


}
   export default TempChart;

但结果我得到了这样的错误错误

我知道在 React 15.5 版之后,您必须从 prop-types 导入 PropTypes,如下所示:

import PropTypes from 'prop-types';

或者

var PropTypes = require('prop-types');

现在我的问题是我在哪里导入它,因为所有 D3 文件都使用导致问题的旧 PropType 并且 D3 库中有很多文件我无法在每个文件中导入新文件。

这是我的 package.json 文件:

{
  "name": "d3app",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "react": "^16.4.1",
    "react-d3-basic": "^1.6.11",
    "react-dom": "^16.4.1",
    "react-scripts": "1.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  }
}

标签: javascriptreactjsd3.jsreact-d3

解决方案


看来是图书馆的问题。它目前使用旧版本的 React (v 0.14) 作为对等依赖项。就像你说的 15.5 更改为prop-types. 您可以分叉库并进行更改prop-types(例如:https ://github.com/react-d3/react-d3-basic/pull/51/files ),但它需要由库维护者修复。

这是一个更详细的问题:https ://github.com/react-d3/react-d3-basic/issues/56


推荐阅读