如何将n_data模块的模拟API数据处理后渲染为react-native-svg-charts面积图
问题原因
- 直接修改state值:React要求所有state变更必须通过
setState方法触发,直接操作this.state属性不会触发组件重渲染,render函数始终拿不到更新后的数据。 - 数据结构不符合图表要求:
this.state.data.map返回的x本身就是一维数值数组,直接push到new_data会生成二维数组,而AreaChart的data参数要求传入一维数值数组,结构不匹配无法渲染。
修复后的代码
import React, { Component } from 'react'; import { View } from 'react-native'; import n_data from './data' import { AreaChart, Grid } from 'react-native-svg-charts' import * as shape from 'd3-shape' class MyComponent extends Component { constructor() { super() this.state = { data: n_data, new_data: [] } } componentDidMount() { const newData = this.state.data.map(item => parseFloat(item.volume)) this.setState({ new_data: newData }) } render() { const { new_data: data } = this.state return ( <View> <AreaChart style={{ height: 200 }} data={data} contentInset={{ top: 30, bottom: 30 }} curve={shape.curveNatural} svg={{ fill: 'rgba(134, 65, 244, 0.8)' }} > <Grid /> </AreaChart> </View> ); } } export default MyComponent;
内容的提问来源于stack exchange,提问作者code_novice_1234
相关产品推荐
相关产品推荐

