Reactjs 如何在React中更新地理位置状态?

Reactjs 如何在React中更新地理位置状态?,reactjs,Reactjs,我正在尝试获取用户的地理位置,并用纬度和经度更新状态。我遵循了,但是我得到了一个错误,成功是未定义的,尽管我根据文档定义了它。我怎样才能使这个代码工作 类应用程序扩展了React.Component{ state={纬度:null,经度:null}; componentDidMount(){ window.navigator.geolocation.getCurrentPosition( success=>this.state.latitude= success.coords.latitude,

我正在尝试获取用户的地理位置,并用纬度和经度更新状态。我遵循了,但是我得到了一个错误,成功是未定义的,尽管我根据文档定义了它。我怎样才能使这个代码工作

类应用程序扩展了React.Component{
state={纬度:null,经度:null};
componentDidMount(){
window.navigator.geolocation.getCurrentPosition(
success=>this.state.latitude=
success.coords.latitude,this.state.longitude=success.coords.longitude
);
}
render(){
返回{this.state.latitude},{this.state.longitude};
}
}

此错误在控制台中可能会有点混淆,因为该错误实际上不是关于
成功
,而是关于
引用
成功
。您没有正确分配状态。必须使用
setState
更改状态。不能通过直接为状态指定新值来更改状态

class App extends React.Component {
    state = { latitude: null, longitude: null };

    componentDidMount() {
        window.navigator.geolocation.getCurrentPosition(
            success => this.setState({ latitude: success.coords.latitude, longitude: success.coords.longitude })
        );
    }

    render() {
        return <div>{this.state.latitude}, {this.state.longitude}</div>;
    }
}
类应用程序扩展了React.Component{
state={纬度:null,经度:null};
componentDidMount(){
window.navigator.geolocation.getCurrentPosition(
success=>this.setState({latitude:success.coords.latitude,longitude:success.coords.longitude})
);
}
render(){
返回{this.state.latitude},{this.state.longitude};
}
}
您可以阅读有关关键字
this
的更多信息。如果您要在React.js中工作,这是一个非常重要的概念