【发布时间】:2018-05-25 13:03:23
【问题描述】:
我正在使用 Axios 在 ReactJS 中获取 API 数据。我设置了一个搜索查询,它将获取用户输入并将其与数据响应设置为状态的 API 匹配。我遇到了一个问题,如果我尝试接收的数据在 API 中不存在,则页面返回并显示以下错误:
Unhandled Rejection (TypeError): Cannot read property 'medium' of null
32 | title: response.data.name,
33 | summary: response.data.summary,
34 | rating: response.data.rating.average,
> 35 | image: response.data.image.medium,
36 | genre: response.data.genres,
37 | });
38 | })
有没有办法在 GET 请求中编写 if/else 语句来解决这个问题?
import React, { Component } from 'react';
import SearchResults from '../SearchResults/SearchResults';
import AddButton from '../AddButton/AddButton';
import axios from 'axios';
class Searchbar extends Component {
constructor(props) {
super(props);
this.state = {
searchTerm: ' ',
title: ' ',
summary: ' ',
rating: ' ',
image: ' ',
genre: [],
}
}
componentWillMount() {
this.search();
}
updateSearchHandler = (event) => {
this.search(this.refs.query.value);
}
search(query = "stranger-things") {
const url = `http://api.tvmaze.com/singlesearch/shows?q=${query}`;
axios.get(url).then(response => {
this.setState({
title: response.data.name,
summary: response.data.summary,
rating: response.data.rating.average,
image: response.data.image.medium,
genre: response.data.genres,
});
})
}
render() {
let editedSummary = this.state.summary.replace(/(<p>|<b>|<\/p>|<\/b>)/g, '')
let spiltGenre = this.state.genre.join(', ');
return(
<div>
<input
type="text"
ref="query"
onChange={this.updateSearchHandler}/>
<SearchResults
showTitle={this.state.title}
showSummary={editedSummary}
showRating={this.state.rating}
showImage={this.state.image}
showGenre={spiltGenre}/>
<AddButton
showTitle={this.state.title}
showGenre={spiltGenre}/>
</div>
)
}
}
export default Searchbar;
【问题讨论】:
标签: javascript ajax reactjs api axios