reactjs - 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;
解决方案
在调用 ComponentDidMount 之前,渲染函数将使用初始道具和状态运行。您确实将初始状态设置为datacharts: ""
,这是一个字符串。但是 String 没有方法String.map()
,所以它出错了。
我建议在构造函数中使用,this.state = { datacharts: [] }
推荐阅读
- python - 使用列表推导将已排序、转换为整数的列表转换回字符串
- python - PyCharm 区分大小写的自动完成
- c++ - 通过解析流量检测 TCP 连接
- elasticsearch - 配置标准分词器 elasticsearch
- gcc - 如何验证可执行文件中的 getaddrinfo 版本
- node.js - 如何在命令行执行期间设置密码
- mysql - MySQL Ver 15.1 不分区表
- laravel - 在 Laravel API 资源中返回数组而不重新排序键
- angularjs - AngularJS如何在Promise返回时更新GUI
- javascript - JavaScript 迭代键并创建 div 元素