首页 > 解决方案 > 使 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 块之外获取更改的值?

标签: javascriptreactjsecmascript-6

解决方案


您可以使用临时变量来获取 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)
}

推荐阅读