React类组件遍历用户数据绘制饼图出错排查求助
问题分析与修复
你的代码存在两个关键问题,导致饼图无法正常渲染:
1. setState 调用错误
在componentDidMount中,你直接将API返回的用户数组赋值给state,但正确的做法应该是更新state中的users字段,而非覆盖整个state对象。
原错误代码:
const s = response.data.users; this.setState(s);
修正后:
const users = response.data.users; this.setState({ users });
若直接传数组s,会把整个state替换成数组,后续this.state.users会变为undefined,导致map遍历失败。
2. dataPoints 嵌套错误
你在dataPoints中给map的结果额外包裹了一层数组,导致最终dataPoints是二维数组([ [{}, {}, ...] ]),但CanvasJS要求的是一维对象数组。
原错误代码:
dataPoints: [ this.state.users.map((user) =>( { y:user.points, label:user.name} )) ]
修正后:
dataPoints: this.state.users.map((user) => ({ y: user.points, label: user.name }))
去掉外层数组包裹,直接使用map返回的一维数组即可。
完整修正后的代码
import React, { Component } from 'react'; import CanvasJSReact from './canvasjs.react'; import axios from 'axios'; var CanvasJS = CanvasJSReact.CanvasJS; var CanvasJSChart = CanvasJSReact.CanvasJSChart; class Dashboard extends Component { constructor(props) { super(props); this.state = { users: [], }; } componentDidMount() { axios .post("http://127.0.0.1:8000/api/v1/users/get_users", { company_id: localStorage.getItem("company_id") }) .then((response) => { const users = response.data.users; this.setState({ users }); }); } render() { const options = { animationEnabled: true, exportEnabled: true, theme: "dark2", title:{ text: "Trip Expenses" }, data: [{ type: "pie", indexLabel: "{label}: {y}%", startAngle: -90, dataPoints: this.state.users.map((user) => ({ y: user.points, label: user.name })) }] } return ( <div> <CanvasJSChart options={options}/> </div> ); } } export default Dashboard;
额外提醒:请确认user.points是数值类型,如果接口返回的是字符串,需要先转为数字(比如y: Number(user.points)),否则CanvasJS可能无法正确解析数据。
内容的提问来源于stack exchange,提问作者user18392765
相关产品推荐
相关产品推荐

