【发布时间】:2018-12-30 23:19:11
【问题描述】:
您好,我需要在我的 API 获取中添加一个状态,但很难理解为什么当状态为空字符串时它可以工作,但如果状态内有字符串则无法工作,请查看示例
这个想法是用户在输入中输入新文本,更新状态搜索,然后更新获取 url,以便他们可以搜索数据库
示例工作代码(注意状态搜索为空)
export default class ThirdScreen extends React.Component {
state = {
search: '',
image: ''
}
componentDidMount() {
this.fetchsa();
}
fetchsa = () => {
const {search} = this.state;
fetch(`https://xxx/search?q=moon&media_type=image`)
.then((response) => response.json())
.then((result) => this.setState({
image: result.collection.items[0].links[0].href
}))
}
示例代码无效
export default class ThirdScreen extends React.Component {
state = {
search: 'moon', //Notice this is not empty and now causes an error
image: ''
}
componentDidMount() {
this.fetchsa();
}
fetchsa = () => {
const {search} = this.state;
fetch(`https://xxx/search?q='${search}'&media_type=image`)
.then((response) => response.json())
.then((result) => this.setState({
image: result.collection.items[0].links[0].href
}))
}
【问题讨论】:
-
你的错误在
result.collection.items[0].links这种解构很容易出错。你确定 api 的响应有预期的结果吗?
标签: json reactjs api react-native