首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >TypeError: this.state.datacharts.map不是函数

TypeError: this.state.datacharts.map不是函数
EN

Stack Overflow用户
提问于 2019-04-27 02:43:54
回答 1查看 65关注 0票数 0

请帮帮忙,我的代码出了问题,我看到了一些类似的问题,但没有找到为什么会发生这种情况。我收到一个错误。TypeError: this.state.datacharts.map不是函数..请帮助错误在哪里,因为我只是反应这是我的代码:

代码语言:javascript
复制
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;
EN

回答 1

Stack Overflow用户

发布于 2019-04-27 03:07:42

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

我推荐在构造函数中使用this.state = { datacharts: [] }

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55873356

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档