请帮帮忙,我的代码出了问题,我看到了一些类似的问题,但没有找到为什么会发生这种情况。我收到一个错误。TypeError: this.state.datacharts.map不是函数..请帮助错误在哪里,因为我只是反应这是我的代码:
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;发布于 2019-04-27 03:07:42
在调用ComponentDidMount之前,render函数将以初始属性和状态运行。您确实将初始状态设置为datacharts: "",它是一个字符串。但是String没有String.map()方法,所以它会出错。
我推荐在构造函数中使用this.state = { datacharts: [] }
https://stackoverflow.com/questions/55873356
复制相似问题