使用保存特定加密貨幣硬幣的對象數組的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:[]}' –