因此,每当我点击刷新按钮并且stocks.stock应该更新时,我想调用Google财经API。到目前为止,我已经编写了以下代码,现在我不知道如何继续进行。
浏览器出现以下错误:未捕获的TypeError:e.currentTarget.data不是函数。
谢谢
class App extends React.Component{
constructor(){
super();
this.state = {
stocks:[
{"ID":"1", "stock":"AAPL", "price": "$785.34",
"industry":"Tech"},
{"ID":"2", "stock":"WMT", "price": "$68.75",
"industry":"Tech"},
{"ID":"3", "stock":"AMZN", "price": "$810.45",
"industry":"Tech"},
{"ID":"4", "stock":"FB", "price": "$95.34",
"industry":"Tech"},
],
};
}
updateStock(e){
var stock = (e.currentTarget).data('stock');
var url=`https://www.google.com/finance/info?q=NASDAQ:${stock}`;
axios.get(url).then(response => {
var json = parser.parse(response.data);
let store = this.state.stocks;
store.price = json.l;
this.setState({
stocks: store
})
});
}
render(){
return (
<table>
<thead>
<tr>
<th> ID</th>
<th> stock</th>
<th> price</th>
<th> industry</th>
</tr>
</thead>
<tbody>
{
this.state.stocks.map((stocks) => {
return (
<tr>
<td>{stocks.ID}</td>
<td>{stocks.stock}</td>
<td>{stocks.price}</td>
<td>{stocks.industry}</td>
<td> <button onClick=
{this.updateStock}
data-stock=
{this.state.stocks.stock}>
refresh
</button>
</td>
</tr>
);
})
}
</tbody>
</table>
</div>
);
}
}
答案 0 :(得分:0)
试试这个:
class App extends React.Component {
constructor(props){
super(props)
this.state = {
stocks:[
{"ID":"1", "stock":"AAPL", "price": "$785.34",
"industry":"Tech"},
{"ID":"2", "stock":"WMT", "price": "$68.75",
"industry":"Tech"},
{"ID":"3", "stock":"AMZN", "price": "$810.45",
"industry":"Tech"},
{"ID":"4", "stock":"FB", "price": "$95.34",
"industry":"Tech"},
],
};
}
updateStock(stock){
// var stock = (e.currentTarget).data('stock');
var url=`https://www.google.com/finance/info?q=NASDAQ:${stock}`;
axios.get(url).then(response => {
var json = parser.parse(response.data);
let store = this.state.stocks;
store.price = json.l;
this.setState({
stocks: store
})
});
}
render(){
return (
<div>
<table>
<thead>
<tr>
<th> ID</th>
<th> stock</th>
<th> price</th>
<th> industry</th>
</tr>
</thead>
<tbody>
{
this.state.stocks.map((stocks, i) => {
return (
<tr key={i}>
<td>{stocks.ID}</td>
<td>{stocks.stock}</td>
<td>{stocks.price}</td>
<td>{stocks.industry}</td>
<td> <button onClick={() => {
{this.updateStock(stocks.stock)}
}}>refresh</button>
</td>
</tr>
);
})
}
</tbody>
</table>
</div>
);
}
}
答案 1 :(得分:0)
在这一行var stock = (e.currentTarget).data('stock');
中,应该在jQuery元素上调用.data()
,在(e.currentTarget)
上调用它不是jQuery元素。
答案 2 :(得分:0)
将此行添加到构造函数()中: this.updateStock = this.updateStock.bind(this);
constructor(props){
super(props);
// ...
this.updateStock = this.updateStock.bind(this);
}