我有一个组件说HomePage,我要在其中调用getCurrentLocation
以使用GPS获取位置。该值将用于从下拉菜单中选择一个值。然后,用户可以使用下拉菜单更改值。
当我离开此页面然后返回使用
const appHistory = createHashHistory();
appHistory.goBack();
构造函数和componentDidMount再次执行。所以用户选择的值丢失了,我又得到了默认值。
那么我应该在哪里放置初始化代码?我来自Ionic,那里有ionViewDidLoad之类的东西,仅在页面首次加载时才执行。是否有与此等效的React。
下面是我的代码
export class HomePage extends React.Component {
constructor(props){
super(props);
state = {
currentLocationCoordinates:[],
};
this.getCurrentLocation = this.getCurrentLocation.bind(this);
}
getCurrentLocation(){
navigator.geolocation.getCurrentPosition((success)=>{
console.log("Current Location: "+success.coords);
this.setState({
currentLocationCoordinates:[success.coords.latitude,success.coords.longitude],
userLocationCoordinates:[success.coords.latitude,success.coords.longitude]
});
});
}
}
componentDidMount(){
this.getCurrentLocation();
}
}
我会避免componentDidMount
为此使用。使您的组件尽可能具有弹性,以便重新渲染和重新安装。
从声音上看,您位于一个应用程序级别状态容器之后,该容器将保持您的应用程序状态,而不管是否安装了组件。
尽管确实存在其他状态容器,但大多数React社区都依赖Redux。我建议您看看Redux,并在Redux商店中使用它来保存这些位置详细信息。这样,无论它们是否重新渲染,它们都将始终在您的组件上作为prop进行访问。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句