【问题标题】:Cannot get data formatted correctly for apexcharts无法为 apexcharts 正确格式化数据
【发布时间】:2020-03-11 12:01:14
【问题描述】:

我从 API 接收到这样的数据

{
    "Bob Knight": 30774.72000002,
    "Samuel Herman": 10310.61000004,
    "Lucie Perry": 26308.41,
    "Andreas Smith": 8960.189999999999,
    "Frederic Smith": 2029.5000000599998,
}

我正在尝试在我的反应应用程序中使用顶点图表在条形图中显示它,但是我似乎无法以正确的方式格式化数据以使顶点显示任何内容。我尝试过像这样在javascript中格式化:

{
    {x: "Bob Knight", y:"30774.720002"},
    ...
}

这似乎是文档建议的内容,但它没有呈现任何内容。以下是我的组件的有用部分

constructor(props) {
        super(props);
        this.state = {
            options: {
                chart: {
                    id: "basic-bar"
                },
                xaxis: {
                    type: 'category'
                }
            },
            values: []
        }
    }

    componentDidUpdate(prevProps) {
        if (!equal(this.props.selectedDate, prevProps.selectedDate))
        {
            var m = moment(this.props.selectedDate).format("M");
            var y = moment(this.props.selectedDate).format("YYYY");
            axios.get('http://localhost:8080/opportunity/owner/' + y + '/' + m)
                .then(res => {
                    values = res.data;
                    this.setState({
                        values
                    })
                })
                .catch(console.log)
        }
    }

render(
<Chart series = {this.state.values} type ='bar' options ={this.state.options}/>

【问题讨论】:

    标签: javascript reactjs apexcharts


    【解决方案1】:

    const obj = {
      "Bob Knight": 30774.72000002,
      "Samuel Herman": 10310.61000004,
      "Lucie Perry": 26308.41,
      "Andreas Smith": 8960.189999999999,
      "Frederic Smith": 2029.5000000599998,
    }
    
    const arr = Object.entries(obj).map(x => ({
      'x': x[0],
      'y': x[1]
    }))
    console.log(arr)

    【讨论】:

    【解决方案2】:

    查看这个codesandbox,我实现了一个简单的条形图,data 是 y 轴值,xaxis 中的 categories 是 x 轴标签。所以从对象中你可以像这样将它们分开

    const obj = {
     "Bob Knight": 30774.72000002,
     "Samuel Herman": 10310.61000004,
     "Lucie Perry": 26308.41,
     "Andreas Smith": 8960.189999999999,
     "Frederic Smith": 2029.5000000599998
    };
    let categories = Object.keys(obj);
    let data = Object.keys(obj).map(k => obj[k]);
    

    这样做后,将类别和数据设置为这样的状态

    this.setState({
      values: [...this.state.series, { data }],
      options: { ...this.state.options, xaxis: { categories } }
    });
    

    您必须将类别添加到options 对象中的xaxis 并将数据添加到values 数组

    【讨论】:

    • 我收到错误“道具类型失败:无效道具series 提供给object 类型r,预期array”使用此
    • 我已经编辑了我的答案,你能检查一下这是否解决了你的错误
    • 有人可以帮忙吗? stackoverflow.com/questions/62590738/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-10
    • 1970-01-01
    • 1970-01-01
    • 2021-11-16
    相关资源
    最近更新 更多