在Rails中集成Victory图表报错:React子元素不能为对象
问题
我正尝试使用Shakapacker和React On Rails gem在Ruby on Rails(RoR)应用中集成Victory图表。Hello World示例可正常运行,但使用Victory官方文档中的代码时,出现如下错误:
import PropTypes from 'prop-types'; import React, { useState } from 'react'; import style from './HelloWorld.module.css'; import { VictoryBar, VictoryChart, VictoryAxis, VictoryTheme, VictoryStack } from 'victory'; const HelloWorld = (props) => { const v_data = [ {quarter: 1, earnings: 13000}, {quarter: 2, earnings: 16500}, {quarter: 3, earnings: 14250}, {quarter: 4, earnings: 19000} ]; return ( <><div> <h1>Victory Tutorial {props.data}</h1> <VictoryChart domainPadding={10} theme={VictoryTheme.material} > <VictoryAxis tickValues={["Quarter 1", "Quarter 2", "Quarter 3", "Quarter 4"]} /> <VictoryAxis dependentAxis tickFormat={(x) => (`$${x / 1000}k`)} /> <VictoryStack colorScale={"warm"} > <VictoryBar data={v_data} x={"quarter"} y={"earnings"} /> </VictoryStack> </VictoryChart> </div></> ); }; export default HelloWorld;
错误信息:
Uncaught Error: Objects are not valid as a React child (found: object with keys {label, value}). If you meant to render a collection of children, use an array instead.
这似乎和传递对象作为React子元素有关,但这是文档中的标准语法,请问我哪里出错了?
解决方法
1. 修正VictoryAxis的刻度配置
你的数据中quarter是数字类型(1-4),但你给VictoryAxis的tickValues传了字符串数组,导致Victory无法正确映射刻度数据,内部生成了{label, value}格式的对象并错误地作为React子元素渲染。需要将tickValues改为与数据匹配的数字数组,再通过tickFormat转换为显示的季度名称:
修改后的VictoryAxis代码:
<VictoryAxis tickValues={[1, 2, 3, 4]} tickFormat={(value) => `Quarter ${value}`} />
2. 检查props.data的渲染逻辑
你的<h1>Victory Tutorial {props.data}</h1>中,如果props.data是对象类型,直接渲染会触发同样的错误。确保props.data是字符串、数字等可直接渲染的类型,或者提取对象的具体属性进行渲染;如果需要临时调试,可以用JSON.stringify转换为字符串:
<h1>Victory Tutorial {typeof props.data === 'object' ? JSON.stringify(props.data) : props.data}</h1>
完整修改后的代码
import PropTypes from 'prop-types'; import React from 'react'; import style from './HelloWorld.module.css'; import { VictoryBar, VictoryChart, VictoryAxis, VictoryTheme, VictoryStack } from 'victory'; const HelloWorld = (props) => { const v_data = [ {quarter: 1, earnings: 13000}, {quarter: 2, earnings: 16500}, {quarter: 3, earnings: 14250}, {quarter: 4, earnings: 19000} ]; return ( <div> <h1>Victory Tutorial {typeof props.data === 'object' ? JSON.stringify(props.data) : props.data}</h1> <VictoryChart domainPadding={10} theme={VictoryTheme.material} > <VictoryAxis tickValues={[1, 2, 3, 4]} tickFormat={(value) => `Quarter ${value}`} /> <VictoryAxis dependentAxis tickFormat={(x) => (`$${x / 1000}k`)} /> <VictoryStack colorScale={"warm"} > <VictoryBar data={v_data} x={"quarter"} y={"earnings"} /> </VictoryStack> </VictoryChart> </div> ); }; export default HelloWorld;
内容的提问来源于stack exchange,提问作者mike
相关产品推荐
相关产品推荐

