我想发生的事情:我正在尝试向Google Places API发出请求,目前我正在抓取用户输入(onChange)并将请求发送出去。当来自Google地方信息的回复回来时,我希望会有一系列地方信息。有了这些地点,我想将我的视线状态更新为地点的响应数组。
我的代码:
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)[{…},{…},{…},{…},{…},{…},{…},{…},{…},{…},{…},{… },{…},{…},{…},{…},{…},{…},{…},{…}]
err TypeError:无法在eval读取未定义的属性'data'(Search.jsx:63)
去那里
因此,在我的res.data.results的console.log之后,我得到的正是我想要的,它是一组Google地点。
使用该数组,我想将其分配给我的视线状态,但是出现无法读取undefined的'data'属性的类型错误。这对我来说没有意义,因为我console.log res.data.results并返回了一个数组。我也检查了响应对象,并且上面有一个名为data的属性。
有任何想法吗?
您正在连锁承诺。
这条线
.then((res) => console.log(res.data.results))
将返回undefined
由then()
链中的下一个进行处理的对象。
因此将其更改为
.then((res) => { console.log(res.data.results)); return res })
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句