我使用axios with react来查询alpha vantage api。我有api部分工作。我想弄清楚的是如何映射到我要拉的数据,使其可以从数据中生成项目列表。我想使用map创建一个名为stocks的数组,然后每个项目都有一个对象,我可以使用它的符号,价格,数量,时间戳。我该如何正确地做到这一点?
这是我的地图功能:
axios.get(axios.get(url)
.then(res => {
console.log(res.data['Stock Quotes']);
const stocks = res.data['Stock Quotes'].map((stock) => [{symbol: stock.symbol, price: stock.price}])
})
.catch(error => console.log(error))
)
这是从console.log返回的内容(res.data [' Stock Quotes']);
(3) [{…}, {…}, {…}]
0:{1. symbol: "MSFT", 2. price: "93.8100", 3. volume: "26478373", 4. timestamp: "2018-03-07 16:00:00"}
1:{1. symbol: "FB", 2. price: "183.7000", 3. volume: "19004961", 4. timestamp: "2018-03-07 16:56:26"}
2:{1. symbol: "AAPL", 2. price: "175.0200", 3. volume: "30982083", 4. timestamp: "2018-03-07 16:36:24"}
length:3
这是从console.log(股票)返回的内容;
(3) [Array(1), Array(1), Array(1)]
0:Array(1)
0:{symbol: undefined, price: undefined}
length:1
__proto__:Array(0)
0:Array(1)
1:{symbol: undefined, price: undefined}
length:1
这是我使用
的完整代码import React, { Component } from 'react';
import axios from 'axios';
import SearchBar from './components/search_bar';
import './App.css';
class App extends Component {
constructor() {
super();
this.state = {
stocks: [],
term: null,
value: ''
};
this.handleClick = this.handleClick.bind(this);
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
this.setState({
value: e.target.value
});
}
handleClick(e) {
if(e) e.preventDefault();
this.setState({
value: '',
term: this.state.value,
stocks: this.state.stocks
});
let term = this.state.value;
const key = 'F41ON15LGCFM4PR7';
const url = `https://www.alphavantage.co/query?function=BATCH_STOCK_QUOTES&symbols=${term}&apikey=${key}`;
axios.get(axios.get(url)
.then(res => {
console.log(res.data['Stock Quotes']);
const stocks = res.data['Stock Quotes'].map((stock) => [{symbol: stock.symbol, price: stock.price}])
})
.catch(error => console.log(error))
)
}
render () {
const value = this.state.value;
return (
<div className="App">
<h1>Stock Search</h1>
<SearchBar value={ value }
onChange={ this.handleChange }
onClick={ this.handleClick }/>
</div>
);
}
}
export default App;
答案 0 :(得分:1)
看起来每个“股票报价”“符号”的整个密钥实际上是"1. symbol"
,而不仅仅是"symbol"
(价格是"2. price"
)。
为什么会出现这种情况我不知道,但以下情况应该有效:
const stocks = res.data['Stock Quotes'].map((stock) => [{symbol: stock['1. symbol'], price: stock['2. price']}])