【发布时间】:2017-10-20 23:22:43
【问题描述】:
使用 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 = { value: '', coin: [], items: [], filteredResults: [] }
标签: javascript arrays reactjs filter react-redux