javascript - 使 setState() 改变整个班级的状态变量
问题描述
我有如下代码,如果设备位置可用,它会更改状态内的绳索值。
class App extends Component{
state={
cords:{
longitude:24.01,
latitude:38.22
},
data:{}
}
componentDidMount() {
console.log("Mounted")
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(position=>{
let newCords={
latitude: position.coords.latitude,
longitude: position.coords.longitude
}
this.setState({cords:newCords});
console.log("Inside",this.state);//displays new values
});
};
console.log(this.state);// displays old values
state() 的变化只能在箭头函数内部观察到。如何在整个 if 块之外获取更改的值?
解决方案
您可以使用临时变量来获取 if 块之外的值,它可以通过以下方式使用
componentDidMount() {
let temp={}
console.log("Mounted")
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(position=>{
let newCords={
latitude: position.coords.latitude,
longitude: position.coords.longitude
}
temp=newCords;
this.setState({cords:newCords});
console.log("Inside",this.state);//displays new values
});
};
console.log(this.state);
console.log('temp variable having new data',temp)
}
推荐阅读
- sonarqube - Sonarqube 7.9.1 社区故障排除
- python - 需要使用python根据标题提取内容
- algorithm - 冒泡排序和分布排序算法的“问题大小”是多少?
- terraform-provider-aws - 如何在一个elb下添加多个实例
- python - 如何找到句子的核心上下文
- python - int64 数组和 int 的总和是否应该通过 int64 类型检查?
- c# - 使用非托管内存时出现奇怪的内存使用情况
- python - PYTEST - 如何使 CONFTEST.PY 在其他 python 目录中可用
- jmeter - 无法在另一个请求中使用 Beanshell 预处理器变量
- php - 表格数据输入未按预期工作。它只是在数据库中保存一条记录