何をしたいのか:グーグルプレイス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'))
グーグルプレイスに電話をかけた後の私のコンソール:
(20)[{…}、{…}、{…}、{…}、{…}、{…}、{…}、{…}、{…}、{…}、{…}、{… }、{…}、{…}、{…}、{…}、{…}、{…}、{…}、{…}]
err TypeError:evalで未定義のプロパティ 'data'を読み取れません(Search.jsx:63)
ここに着いた
したがって、res.data.resultsのconsole.logの後で、Googleプレイスの配列である必要なものを正確に取得しました。
その配列を使用して、それを自分の視界の状態に割り当てたいと思いましたが、未定義の「データ」のプロパティを読み取れませんというタイプエラーが発生します。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]
コメントを追加