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

3

我想获取用户的地理位置并使用纬度和经度更新状态。我遵循了Geolocation API MDN文档进行操作,但是我收到一个错误,说success未定义,尽管我已根据文档进行了定义。如何使这段代码正常工作?

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>;
    }

}
1个回答

3

在控制台中,此错误可能会有点令人困惑,因为错误实际上与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>;
    }
}

如果你要在React.js中工作,那么理解关键字 this 是非常重要的概念。你可以在这里了解更多关于它的内容。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接