嗨,我的代码有问题,不知道我做错了什么(我正在大学做我的学位项目,仍然是新手使用 react),事情是我有一个组件获取我的 API 的多个端点,
这是组件中的代码:
数据.js:
import React from 'react';
class Data extends React.Component {
constructor(props){
super(props);
this.state = {
actionData:[],
questionData:[]
};
}
async componentDidMount(){
const url = "https://api-tesis-marco.herokuapp.com/api/v1/users";
const url2 = "https://api-tesis-marco.herokuapp.com/api/v1/questiondata/siete-colores";
const actionData = await fetch(url)
.then(response => response.json());
this.setState({actionData:actionData});
const data = await fetch(url2)
.then(response2 => response2.json());
this.setState({questionData:data});
}
render(){
return ( //here is where i'm having trouble
<dashboard data = {this.state.questionData} />
);
}
}
export default Data;
我不知道如何将 questionData 中的数据传递给这个组件
仪表板.js:
import React , {Component} from 'react';
import Pie from '../../piechart';
import Data from '../Data/Data.js'
class Dashboard extends Component{
render (){
//here is where i want my data
const data = Data;
return(
<div className="dashboard container">
<div className="row">
<div className="col s12 m6">
<Pie data = {data} width={200} height={200} innerRadius={60} outerRadius={100}/>
</div>
</div>
</div>
);
}
}
export default Dashboard;
我想这样做,这样我就可以使用我的数据创建一个 D3.js 饼图
也是我的饼图组件的代码
饼图.js:
import React, { useEffect, useRef } from "react";
import * as d3 from "d3";
const Pie = props => {
const ref = useRef(null);
const createPie = d3
.pie()
.value(d => d.value)
.sort(null);
const createArc = d3
.arc()
.innerRadius(props.innerRadius)
.outerRadius(props.outerRadius);
const colors = d3.scaleOrdinal(d3.schemeCategory10);
const format = d3.format(".2f");
useEffect(
() => {
const data = createPie(props.data);
const group = d3.select(ref.current);
const groupWithData = group.selectAll("g.arc").data(data);
groupWithData.exit().remove();
const groupWithUpdate = groupWithData
.enter()
.append("g")
.attr("class", "arc");
const path = groupWithUpdate
.append("path")
.merge(groupWithData.select("path.arc"));
path
.attr("class", "arc")
.attr("d", createArc)
.attr("fill", (d, i) => colors(i));
const text = groupWithUpdate
.append("text")
.merge(groupWithData.select("text"));
text
.attr("text-anchor", "middle")
.attr("alignment-baseline", "middle")
.attr("transform", d => `translate(${createArc.centroid(d)})`)
.style("fill", "white")
.style("font-size", 10)
.text(d => format(d.value));
},
[props.data]
);
return (
<svg width={props.width} height={props.height}>
<g
ref={ref}
transform={`translate(${props.outerRadius} ${props.outerRadius})`}
/>
</svg>
);
};
export default Pie;
这也是我请求的 API 中的数据
数据:
[
{
"Respuesta": "A",
"porcentaje": 7
},
{
"Respuesta": "B",
"porcentaje": 3
},
{
"Respuesta": "C",
"porcentaje": 3
},
{
"Respuesta": "D",
"porcentaje": 10
},
{
"Respuesta": "No ha respondido",
"porcentaje": 76
}
]
我知道那里有很多教程,但我没有找到任何特定于我的案例的教程,我想知道我做错了什么,所以我可以用 4 个不同的 API url 创建 4 个相同的饼图