首页 > 解决方案 > TypeError:this.state.datacharts.map 不是函数

问题描述

请帮忙,我的代码有问题,已经看到一些类似的问题,但没有找到为什么会发生这种情况。我有一个错误。TypeError: this.state.datacharts.map is not a function .. 请帮忙看看错误在哪里,因为我只是 reactjs 这是我的代码:

import React, { Component } from 'react';
import ReactSpeedometer from "react-d3-speedometer"

// Resolves charts dependancy
const API = 'http://localhost:9000/Sales_vs_Target';

class Chart_SalesVsTarget extends Component {
  constructor(props) {
    super(props);
    this.state = { 
      datacharts: '' 
    };
}

callAPI() {
  fetch(API)
      .then(res => res.text())
      // .then(res => this.setState({res}, () => 
      //   console.log('Datacharts fetched...', res)))
      .then(res => this.setState({ datacharts: res }));
}
componentDidMount() {
  this.callAPI();
}

  render() {
    return (
      <div>
        <center><h4>Sales vs Target</h4></center>
      <a href='/Table_nas'>
             <center>
               <div>
             {/* {this.props.apiResponse.map(apiResponses => */}
             <div style={{
                width: '500px',
                height: '300px',
                background: '#e4e5e6'
              }}>
              {this.state.datacharts.map(apiResponses => 
                <ReactSpeedometer
                  fluidWidth
                  minValue={0}
                  maxValue={100}
                  value={apiResponses.PERSEN_NAS}
                />
                )}
              </div>

               </div>
             </center>
         </a>
         </div>
    );
  }
}

export default Chart_SalesVsTarget;

标签: reactjs

解决方案


在调用 ComponentDidMount 之前,渲染函数将使用初始道具和状态运行。您确实将初始状态设置为datacharts: "",这是一个字符串。但是 String 没有方法String.map(),所以它出错了。

我建议在构造函数中使用,this.state = { datacharts: [] }


推荐阅读