我有一个名为 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 存储的一部分。然后,无论组件是否重新渲染,它们都可以作为 props 在您的组件上始终进行访问。
关于javascript - ReactJS 一次性初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50815575/