gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 14:11:53 25 4
gpt4 key购买 nike

我正在尝试获取用户的地理位置并使用纬度和经度更新状态。我关注了the MDN docs for the Geolocation API ,但我收到一个错误,指出成功未定义,即使我根据文档定义了它。我怎样才能让这段代码工作?

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

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

render() {
return <div>{this.state.latitude}, {this.state.longitude}</div>;
}

}

最佳答案

此错误在控制台中可能有点令人困惑,因为该错误实际上与 success 无关,而是 this 引用 success 。您没有正确分配状态。您必须使用 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>;
}
}

您可以阅读有关关键字this的更多信息 here 。如果您打算在 React.js 中工作,那么理解这是一个非常重要的概念。

关于reactjs - 如何在 React 中更新地理位置状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55070289/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com