如何解决如何在不进行硬编码的情况下有效地在react-google-charts中传递数据?
所以我的代码绝对可以正常工作,我的数组使用正确的语法,一切都很好
但是我发现自己在JSX
中手动进行了硬编码数据(在
问题
现在我有20个元素,我将不得不手动对其进行硬编码,这不是非常有效..是否有更好的方法来做到这一点?
import React from 'react'
import Chart from "react-google-charts"
import {useSelector} from 'react-redux'
const Graph = () => {
const products = useSelector(state => state.products)
const colors = ['#51e2f5','#9df9ef','#edf756','#ffa8B6','#a28089','#a0d2eb','#e5eaf5','#d0bdf4','#8458B3','#a28089']
for(var i=0;i<10;i++) {
products[i].color = colors[i]
}
for(i =10;i<20;i++) {
products[i].color = colors[i-10]
}
const arr = products.map((prod) => {
return [prod.productName,parseInt(prod.price),prod.color,null]
})
return (
<Chart
{...console.log(arr[0])}
width={'500px'}
height={'300px'}
chartType="BarChart"
loader={<div>Loading Chart</div>}
data={[
[
'Element','Density',{ role: 'style' },{
sourceColumn: 0,role: 'annotation',type: 'string',calc: 'stringify',},],// ['copper',8.94,'#b87333',null],// ['Silver',10.49,'silver',// this is the data format expected
// ['Gold',19.3,'gold',// ['Platinum',21.45,'color: #e5e4e2',[arr[0][0],arr[0][1],arr[0][2],arr[0][3]],[arr[1][0],arr[1][1],arr[1][2],arr[1][3]],// i want to do this 20 times i.e first index goes till 20 (Now going till 3)
[arr[2][0],arr[2][1],arr[2][2],arr[2][3]],[arr[3][0],arr[3][1],arr[3][2],arr[3][3]],]}
options={{
title: 'Density of PrecIoUs Metals,in g/cm^3',width: 600,height: 400,bar: { groupWidth: '95%' },legend: { position: 'none' },}}
// For tests
rootProps={{ 'data-testid': '6' }}
/>
)
}
export default Graph
解决方法
您可以使用the spread operator
data={[
[
'Element','Density',{ role: 'style' },{
sourceColumn: 0,role: 'annotation',type: 'string',calc: 'stringify',},],...arr
]}
,
我最近从事类似项目。我通过AJAX获取JSON数据,然后需要构建自己的函数以Google Chart接受的形式创建数据。
不用在data属性中对数据进行硬编码,只需创建一个需要以正确格式生成数组的函数即可。然后,该函数应返回您需要的数据,并在data属性中使用它。
您的硬编码方法很好,但是将其转换为函数,就可以了。我要做的是将数据存储在状态中,以防数据更改。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。