我有一个简单的搜索,我创建了在React中显示加密货币价格。
api端点是https://api.coinmarketcap.com/v1/ticker/{id}/
其中id
是硬币的名称。当我获取https://api.coinmarketcap.com/v1/ticker/bitcoin/
的端点时,我得到了
未捕获(在promise中)SyntaxError:意外的输入结束
构造
constructor() {
super();
this.state = {value: ''};
this.state = {coin: []};
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) {
fetch(`https://api.coinmarketcap.com/v1/ticker/${id}`, {
mode: 'no-cors'
}).then((result)=> {
debugger;
result.json()
.then(json => {
debugger;
this.setState({coin: 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: {/* Price here */}
</div>
</div>
);
}
答案 0 :(得分:0)
似乎result.json()
函数失败并出现异常。因为您在承诺链中没有catch()
,所以会抱怨。
尝试将catch()
添加到结尾:
result.json()
.then(json => {
debugger;
this.setState({
coin: json
})
})
.catch(error => {
debugger
console.log(error);
});
答案 1 :(得分:0)
fetch
函数需要将Request
对象传递给它。
https://developer.mozilla.org/en-US/docs/Web/API/Request/Request
例如,
findCoin(id) {
let endpoint = `https://api.coinmarketcap.com/v1/ticker/${id}`;
let request = new Request(endpoint);
return fetch(request).then((body) => {
return body.json().then((json) => {
this.setState({ coin: json });
});
});
},