使用保存特定加密货币硬币的对象数组的api端点。在反应中清除值状态
我创建了一个表单,用户可以输入特定的硬币并点击提交,它会返回价格。然后该硬币将检查它是否在api中的一个对象数组中。如果它是有效的,那么我将它推入构造函数中的过滤结果数组中。
我的第一个搜索查询有效,但当我执行第二次查询搜索并点击提交按钮时,它失败并重新加载页面。
constructor() {
super();
this.state = {value: ''};
this.state = {coin: []};
this.state = {items: []};
this.state = {filteredResults: []};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
handleSubmit(event) {
let coin = this.state.value;
this.findCoin(coin);
event.preventDefault();
}
findCoin(id) {
this.state.items.forEach(function(currency){
if(currency.id === id) {
this.state.filteredResults.push(currency)
}
}, this);
this.setState({filteredResults: this.state.filteredResults[0]});
}
componentDidMount() {
fetch(`https://api.coinmarketcap.com/v1/ticker/`)
.then((result)=> {
result.json()
.then(json => {
this.setState({items: json})
});
});
}
render() {
return (
<div className="App">
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" value={this.state.value} onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
<div> Price: $ {this.state.filteredResults.price_usd}
</div>
</div>
);
}
}
也许不要紧,你的问题,但国家在构造函数的设定可能要看起来像这样:'this.state = {值:“”,硬币:[],项目:[] ,filteredResults:[]}' –