0
ページをロードすると、トリガーgetLocalStorage
の機能がロードされます。これには、search
機能のチェックとトリガがいくつかあります。ページをロードすると、localStorageからクエリを取得しようとしています。 (クエリを変更する)入力を変更してサブミットすると、search
関数がトリガされますが、フェッチされません。代わりに、ページをリフレッシュしてcomponentDidMountを再度ロードしますか?リフレッシュ後、それは完全に動作します。なぜ1回だけリフレッシュするのですか?onclickの後にComponentWillMountが再度レンダリングされます
componentWillMount(){
this.getLocalStorage();
};
getLocalStorage =() => {
//Check if localstorage is supported by browser
if (typeof(Storage) !== "undefined") {
//Check if localstorage item query is defined
if (localStorage.getItem("query") !== null) {
//Set query to localstorage item and go to search function
//This works and triggers the search function
this.setState({
query: localStorage.getItem("query")
},() => {
this.search();
});
}
// If localstorage item is not defined go to location
else{
this.getLocation();
}
}
// If localstorage is not supported by the browser go to location
else {
this.getLocation();
}
};
ボタンをクリックすると、検索機能が起動されますが、フェッチしません。代わりに、componentDidMountを再度トリガーしますか?
<input type="text" onChange={this.handleChange} placeholder="Find your location..."/>
<button onClick={this.search}>Submit</button>
検索機能
search =() => {
this.setState({
secondLoader:true
});
let BASE_URL = "https://maps.googleapis.com/maps/api/geocode/json?";
let ACCES_TOKEN = "token";
let FETCH_URL = `${BASE_URL}address=${this.state.query}&key=${ACCES_TOKEN}`;
alert('the search function does not fetch like below instead it trigger componentDidMount again');
fetch(FETCH_URL, {
method: "GET"
})
.then(response => response.json())
.then(json => {
//If repsonse got zero results use amsterdam location
if(json.status === 'ZERO_RESULTS'){
this.setState({
query: 'Amsterdam'
});
}
//Otherwise use query
else {
const geocode = json.results[0].geometry.location;
this.setState({
latitude: geocode.lat,
longitude: geocode.lng
});
}
const BASE_URL = "https://api.darksky.net/forecast/";
const ACCES_TOKEN = "token";
const FETCH_URL = `${BASE_URL}${ACCES_TOKEN}/${this.state.latitude},${this.state.longitude}?lang=nl&units=si`;
fetch(FETCH_URL, {
method: "GET",
})
.then(response => response.json())
.then(json => {
const data = json;
this.setState({
weather: data,
loader: false,
secondLoader: false
});
})
})
};
いつクエリをlocalStorageに保存しますか? setStateは非同期であることに注意してください。つまり、setState()を呼び出した直後に状態が更新されることは期待できません。 –
'getLocation'関数でクエリを保存します。 setStateは非同期なので、コールバックを追加して 'search'関数を起動させなければなりませんでした。それはおそらくそれが再びそれをレンダリングする問題ですか? – twoam
'handleChange'と' getLocation'コードで質問を更新することはできますか? –