【发布时间】:2018-05-20 09:48:55
【问题描述】:
我想要发生的事情: 我正在尝试向 google places API 发出请求,目前我获取用户输入(onChange)并将请求发送出去。当来自谷歌地方的响应回来时,我期待一系列地方。有了这些地点数组,我想将我的视线状态更新为地点的响应数组。
我的代码:
import React, {Component} from 'react';
import axios from 'axios';
class Search extends Component {
constructor(props) {
super(props);
this.state= {
sights: 'cat',
city:''
}
}
onInputChange(city) {
this.setState({city});
this.handleSubmit(city);
}
handleSubmit(event) {
axios.get(
"https://maps.googleapis.com/maps/api/place/textsearch/json?query=attractions+in+" +
this.state.city +
"&key=AIzaSyC5d4W-ei6o_C3eCrnJl24nuaeuAemhoJQ",
{
mode: "no-cors",
header: {
"Access-Control-Allow-Orgin": "http://localhost:8080",
"Content-Type": "application/json",
"Access-Control-Allow-Headers":
"Origin, X-Requested-With, Content-Type, Accept"
},
withCredentials: true,
credentials: "same-origin"
}
)
.then((res) => console.log(res.data.results))
.then((res) => {
this.setState({ sights: res.data.results });
})
.then(console.log('got here'))
.catch(function(err) {
console.log("err", err);
})
}
render(){
return (
<div>
<h2>{this.state.city}</h2>
<h4>{this.state.sights}</h4>
<input
value={this.state.city}
onChange={(event)=> this.onInputChange(event.target.value)} />
</div>
)
}
}
export default Search;
我在测试什么:
.then((res) => console.log(res.data.results))
.then((res) => {
this.setState({ sights: res.data.results });
})
.then(console.log('got here'))
调用 google 地方后我的控制台:
(20) [{…}、{…}、{…}、{…}、{…}、{…}、{…}、{…}、{…}、{…}、{…} 、{…}、{…}、{…}、{…}、{…}、{…}、{…}、{…}、{…}]
错误类型错误:无法读取未定义的属性“数据” 在 eval (Search.jsx:63)
到这里
因此,在我的 res.data.results 的 console.log 之后,我得到了我想要的,这是一组 google 位置。
使用该数组,我想将其分配给我的视线状态,但我收到无法读取未定义的“数据”属性的类型错误。这对我来说没有意义,因为我 console.log res.data.results 并取回了一个数组。我也检查了响应对象,上面有一个名为 data 的属性。
有什么想法吗?
【问题讨论】:
-
在第一个
then()中没有返回任何内容以在第二个then()中使用。console.log()返回未定义。
标签: javascript html reactjs