我正在尝试将数据呈现到一个数组中,以便可以在react原生的图表中查看数据。
似乎有一个关于最大值的问题
import React, { Component } from 'react';
import { View,Button,Text } from 'react-native';
import { LineChart, XAxis, Grid } from 'react-native-svg-charts'
import n_data from './data'
class MyComponent extends Component {
constructor() {
super()
this.state = {data:[]}
}
render() {
const restructuredData = n_data.map( (name) => this.setState({data:name.volume}) )
return (
<View>
<Text> {this.state.data} </Text>
</View>
);
}
}
export default MyComponent;我的样本数据是n_data格式的,如下所示
const n_data = [{"timestamp":"2011-08-18T00:00:00Z","volume":"5","spot_volume":"5","derivative_volume":"0"}]发布于 2021-05-30 14:14:07
您可以像这样使用map函数。您的restructuredData最终将导致最大调用深度错误,因为setState方法被多次调用,并将导致组件重新呈现为等于n_data数组的长度。
<View>
{n_data &&
n_data.map((item) => (
<Text key = {item.volume}>{item.volume}</Text>
))}
</View>此外,您还尝试在这里将数组呈现为文本组件
<Text> {this.state.data} </Text>这是不正确的。
更新:
这就是更新状态的方法
restructuredData = n_data => {
let updated_n_data = [];
// Object.values(objName) gives the values of an object
Object.values(n_data).map(item => {
updated_n_data = updated_n_data.concat(item.volume);
});
this.setState({
data: updated_n_data,
});
};发布于 2021-05-30 14:32:58
尝试在组件外部格式化数据(这里不需要使用setState ),然后在构造函数中将其设置为初始状态。this.setState()通常会触发呈现。当你直接从render函数内部调用它时,可能会有一个无限的循环。
另一件事是您试图呈现一个数组,正如前面提到的Rohit。
发布于 2021-05-30 18:32:38
你的错误是因为你在一个渲染函数中重置状态,该函数将尝试重新渲染组件。您将需要修改您的组件,下面是一个快速示例
import React, { Component } from 'react';
import { View,Button,Text } from 'react-native';
import { LineChart, XAxis, Grid } from 'react-native-svg-charts'
import n_data from './data'
class MyComponent extends Component {
constructor() {
super()
let data= null;
n_data.map(name=>{data=name.volume});
this.state = {data}
}
render() {
return (
<View>
<Text> {this.state.data} </Text>
</View>
);
}
}
export default MyComponent;https://stackoverflow.com/questions/67756776
复制相似问题