【发布时间】:2020-07-06 16:42:49
【问题描述】:
我有如下代码,如果设备位置可用,它会更改状态内的绳索值。
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-block 之外获取更改的值?
【问题讨论】:
-
这个答案可能对你有帮助stackoverflow.com/a/30783011/8240417
-
它立即调用了控制台。尝试添加
setTimeout。相反,你应该使用setState的回调函数。
标签: javascript reactjs ecmascript-6