使用create-react-app,我创建了一个简单的React应用,以显示从Flask端点获取的数据。尽管获取功能可以从HTTP端点获取数据,但是映射功能无法读取检索到的数据。该应用会产生类似
的错误TypeError: Cannot read property 'dataTime' of undefined
(anonymous function)
C:/Users/정보기획팀/Dropbox/yu_project/yu_blog_project/air_quality_react/src/DataList.js:10
7 | return(
8 | <div>
9 | {data.map((datum, i) => {
> 10 | return <Data key={i} time={datum[i].dataTime} pm10={datum[i].pm10Value} pm25={datum[i].pm25Value} />;
| ^ 11 | })}
12 | </div>
13 | )
App.js是
import React, {Component} from 'react';
import './App.css';
import DataList from './DataList';
class App extends Component {
constructor(props) {
super(props);
this.state = {
airData: []
};
}
componentDidMount() {
fetch('http://210.123.33.247/airData')
.then(response => response.json())
.then(data =>
this.setState({
airData: data
})
);
}
render() {
const {airData} = this.state;
console.log('air data from the state ', airData);
return (
<div className="App">
<p>Data from the air quality</p>
<DataList data={this.state.airData} />
</div>
);
}
}
export default App;
DataList.js是
import React from 'react';
import Data from './Data';
const DataList = ({data}) => {
console.log('from DataList', data[0]);
console.log('pm value', data[3]);
return (
<div>
{data.map((datum, i) => {
return (
<Data
key={i}
time={datum[i].dataTime}
pm10={datum[i].pm10Value}
pm25={datum[i].pm25Value}
/>
);
})}
</div>
);
};
export default DataList;
Data.js是
import React from 'react';
const Data = ({time, pm10, pm25}) => {
return (
<div>
<p>{pm10}</p>
<p>{pm25}</p>
<p>{time}</p>
</div>
)
}
export default Data
index.js是
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
serviceWorker.unregister();
如果有人请帮助我找到错误,我将不胜感激。非常感谢。
答案 0 :(得分:1)
map
函数是一个for循环,其第一个参数是对象而不是索引,即
{data.map((datum, i) => {
return (
<Data
key={i}
time={datum[i].dataTime}
pm10={datum[i].pm10Value}
pm25={datum[i].pm25Value}
/>
);
})}
应更改为:
{data.map((datum, i) => {
return (
<Data
key={i}
time={datum.dataTime}
pm10={datum.pm10Value}
pm25={datum.pm25Value}
/>
);
})}
答案 1 :(得分:0)
map
是一个for
循环,将无法在return
语句中执行。因此,删除主要的return语句,并将const
更改为下面的代码段
const DataList = ({data}) => {
{data.map((datum, i) => {
return (
<Data
key={i}
time={datum[i].dataTime}
pm10={datum[i].pm10Value}
pm25={datum[i].pm25Value}
/>
);
})}
);
};
要获取错误说明dataTime for undefined
,请检查flask
的入站/传入数据是否在哈希内包含哈希,如果需要,则必须使用Object.values(data.map((dataum, i) => {function})