2017-09-21 94 views
0

为什么我的状态没有设置为变量lat?

let lon, lat; 
 
let weather; 
 
if (navigator.geolocation) { 
 
    navigator.geolocation.getCurrentPosition(function(position) { 
 
    lat = position.coords.latitude; 
 
    lon = position.coords.longitude; 
 
console.log(typeof lat) 
 
}); 
 
} 
 
class Button extends React.Component{ 
 
state = {latt: lat} 
 
\t \t render(){ 
 
\t \t \t return(
 
\t \t <div> 
 
{this.state.latt} 
 
<h1>ss</h1> 
 
</div> 
 
\t \t \t 
 
)}} 
 

 
class Appp extends React.Component { 
 

 
\t render(){ 
 
\t \t return(
 
\t \t \t <Button /> 
 
\t \t)} 
 
\t } 
 
ReactDOM.render(<Appp />, mountNode)

what i did

当我CONSOLE.LOG可变我得到一个号码,但为什么不能我用它作为状态的值。即使将它放入数组也没有区别。

+2

请相关的代码添加到您的问题改变的状态。处理外部图像很困难。 –

+0

你可以在这里发布你的代码来帮助调试吗? – Rowland

+0

由于'getCurrentPosition'不同步,所以当lat被调用时,你的lat,lon不会被填充。相反,您应该在组件中移动此代码并使用'setState'来设置lat和long。 – Panther

回答

0

它应该是这样的:

let lat, lon, weather; 

class Calendar extends React.Component { 
    constructor(props){ 
     super(props); 
     this.state = { 
      lat: null, 
      lon: null 
     } 
     this.updateLatLon = this.updateLatLon.bind(this); 
    } 
    updateLatLon(){ 
     if (navigator.geolocation) { 
      navigator.geolocation.getCurrentPosition((position) => { 
       this.setState(() => { 
        return {lat: position.coords.latitude, lon: position.coords.longitude} 
       }); 
      }); 
     } 
    } 
    componentWillMount(){ 
     this.updateLatLon(); 
    } 
    render(){ 
     return (
      <div> 
       {this.state.lat} 
      </div> 
     ) 
    } 
} 
+0

我认为你的意思是构造而不是构造。尽管如此,两种方式不工作 – Zamir

+0

嗯,应该肯定工作。我对代码进行了一些更改,可能会使其工作?不确定。尝试并告诉我你收到了哪些错误 –

+0

你忘记关闭navigator.geolocation.getCurrentPosition函数后的括号。但仍然两种方式都没有工作。它没有显示任何状态是未定义的 – Zamir

0

通过使用setState()

navigator.geolocation.getCurrentPosition(function(position) { 
    this.setState({ 
     lat: position.coords.latitude, 
     lon: position.coords.longitude 
    }); 
    console.log(typeof lat) 
}); 
+0

中的何处和何时被绑定? – Zamir

+0

好问题,我编辑了我的答案 – MatTheWhale

+0

我应该在哪里添加?即时消息得到意想不到的令牌 – Zamir

相关问题