无法在 React 中呈现数据

Trouble rendering data in React

我正在尝试将数据从 VictoryChart 馈送到饼图中。实现图形非常容易。要实现 pie graph,您只需执行以下操作...

<VictoryPie
  data={[
    { x: "Cats", y: 35 },
    { x: "Dogs", y: 40 },
    { x: "Birds", y: 55 }
  ]}
/>

注意 data 格式,它是某种关联数组的数组 [{...},{...}]

现在,在我的状态下,我有一个叫做 pie_datapie_keys 的东西。本质上,pie_data 只是一个对象...

{
  "Fac of Engineering & Appl Sci": 8.557902403495994,
  "Faculty of Arts and Science": 53.775188152464196,
  "Faculty of Education": 13.085700412721534,
  "Faculty of Health Sciences": 7.75673707210488,
  "Faculty of Law": 8.07234765719835,
  "Not Faculty Specific": 0.30347171643602816,
  "School of Business": 5.8994901675163876,
  "School of Graduate Studies": 2.537023549405195,
  "School of Religion": 0.012138868657441126
}

pie_keys 只是查找值...

 ["Fac of Engineering & Appl Sci", "Faculty of Arts and Science", etc.]

pie_keys 仅用于查找 pie_data 中的值。所以,基本上,如果我想创建一个饼图,我会开始实施以下...

<VictoryPie
  data={[
    { x: "Fac of Engineering & Appl Sci", y: 8.557902403495994 },
    { x: "Faculty of Arts and Science", y: 53.775188152464196 },
    { x: "Faculty of Education", y: 13.085700412721534 },
    ...
    ...
  ]}
/>

但我不能手动完成。我需要从状态值中提取它们。所以我尝试了以下...

render() {
    const data_distribution = [this.state.pie_keys.map((d) => {x:d, y:this.state.pie_data[d]})];
    return (
      <div className="App">
        <VictoryPie
          data = {data_distribution}
        />
      </div>
    );
  }

地图函数按预期工作,我已经对其进行了测试,x 是键值,y 是与该键关联的值。但是,我的问题是以 [{x:.., y:...}, {x:..., y:...}, etc.] 的预期格式返回 data_distribution。当我尝试上面的示例时,我收到一条错误消息...

Syntax error: Unexpected token, expected ; 
(57:69) 55 | 56 | render() { > 57 | const data_distribution = [this.state.pie_keys.map((d) => {x:d, y:this.state.pie_data[d]})]; 
                                                                                                   | ^

如何将正确的格式输入饼图?

替换

const data_distribution = [this.state.pie_keys.map((d) => {x:d, y:this.state.pie_data[d]})];

const data_distribution = this.state.pie_keys.map((d) => ({x:d, y:this.state.pie_data[d]}));

首先有两个问题 Array.map 本身 return 是一个 数组 。所以不需要将 data_distribution 包装在 [].

第二个问题是围绕线

(d) => {x:d, y:this.state.pie_data[d]}

这里的函数试图 return 来自箭头函数的对象字面量。这将始终 return 未定义。由于解析器不会将两个大括号解释为对象文字,而是作为块 statement.The 括号强制将其解析为对象文字。希望这有帮助