【发布时间】:2019-08-29 21:20:26
【问题描述】:
我正在尝试执行 fetch 调用以返回一个数组,但是,当我尝试使用 map 函数来迭代数组时,编译器给出一个错误,提示无法读取我被卡住的未定义的属性映射,我也对类似问题进行了一些研究,但无济于事。我是 React 的新手,因此我不确定哪个部分会导致错误。我意识到它来自我的 setState 函数调用。
这是我的 App.js 代码:
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class App extends Component {
constructor() {
super();
this.state={
currencies: [],
};
}
handleChange =(event) => {
let initialData = [];
const url = `http://data.fixer.io/api/latest?access_key=ea263e28e82bbd478f20f7e2ef2b309f&symbols=${event.target.value}&format=1`
console.log("the url is: " + url)
fetch(url).
then(data =>{ return data.json();})
.then(findData => {
initialData = findData.rates
console.log(initialData)
this.setState({
currencies: initialData.rates,
});
});
}
render() {
const{currencies} = this.state;
return (
<div className="App">
{ this.state.currencies.map((current) => <div> {current.rates}</div>)}
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<h1 className="App-title"> Welcome to DKK website </h1>
<div class="dropdown">
<select id="select1" name ="currency" value={this.state.selectValue} onChange={this.handleChange}>
<option value="EUR">-- Selecting: NILL --</option>
<option value="CAD">-- Selecting: CAD --</option>
<option value="SGD">-- Selecting: SGD --</option>
<option value="AFN">-- Selecting: AFN --</option>
</select>
</div>
<button className="pressMe" > Set Button </button>
<br/>
<br/>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}
}
export default App;
【问题讨论】:
-
你能
console.log( this.state.currencies)吗?它很可能不是一个数组。 -
是的,它输出 [index,value]
标签: reactjs array.prototype.map