加载页面ComponentWillMount
触发getLocalStorage
功能时。这有几个检查并触发search
功能。当您加载页面时,它正在尝试从localStorage检索查询。当您更改输入(更改查询)并提交时,search
函数应该触发但不提取..而是刷新页面并再次加载componentDidMount?然后在刷新后它完美地工作。为什么它只刷新一次?
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
});
})
})
};