0

我想通过 API 调用获取数值并使用“react-native-chart-kit”在图形中表示它们,但它产生的错误 data[0].toFixed 不是一个函数。如何解决此错误?点击这里查看错误

class SecondActivity extends Component {

 constructor(props){
   super(props);
   this.state={a:"",b:""}
 }

 componentDidMount(){
   this.graph = setInterval( () => this.GetGraph(),1000);
 }

 GetGraph(){
   var jsondata;
  fetch('api here', {
    method: 'GET'
 })
 .then((response) => response.json())
 .then((responseJson) => {
   
   this.setState({
       jsondata: responseJson,
       a:responseJson[0].val,
       b:responseJson[1].val,})
   }) 
 .catch((error) => {
    console.error(error);
 });   } 

  render() {
      if(!this.state.a) {
    return <ActivityIndicator/>
  }
    return (
      <View>
        <LineChart
          data={{
            labels: [
              '1',
              '2', ],
            datasets: [
              {
                data: [
                  this.state.a,
                  this.state.b,                                 
                ],
              },                ],              }}
          width={Dimensions.get('window').width} 
          height={250}
          yAxisLabel="a"
          yAxisInterval={1}/>
      </View>);}}

4

1 回答 1

0

我不知道react-native-chart-kit,但由于toFixed()是一种方法Number,我想responseJson[0].val和/或responseJson[1].val可能包含(一些?)其他值然后是数字。

根据数据,解决方法可能是转换为数字:

this.setState({
    jsondata: responseJson,
    a:responseJson[0].val.map(v => { /* return v converted to number */ },
    b:responseJson[1].val.map(v => { /* return v converted to number */ }
}) 

我不会在这里提供转换。在不知道数据中可能的值的情况下,任何提议都可能是有损的(或者完全是错误的)。

其次,如果服务器要发送号码,它应该发送号码。这可能是一个错误,但也可能有发送数字的原因,例如能够提交高精度数字或无损发送定点小数。在这种情况下,您必须小心如何在 JavaScript 中使用这些值。

如果这不是解决方案,您应该提供原始 JSON 响应以供进一步检查。

于 2020-05-29T08:42:36.663 回答