我目前正在尝试制作一个只有一个屏幕的应用程序,其中屏幕背景由以用户当前坐标为中心的 map 占据。在下面的代码中,我在 App 类组件的状态中将经度和经度保存为 null。然后,我使用继承的方法“componentDidMount()”用用户的当前位置更新状态,最后在 render() 中我使用 this.state.latitude 和 this.state.longitude 来通知纬度和经度的值 map View 。
代码无法编译。使用 console.log,我将问题隔离为 render() 被调用了两次,我的 console.log 语句首先将空值输出到控制台,然后输出用户的当前位置。
所以两个问题。
1)为什么console.log两次向控制台输出值,一次是传入的state值,一次是componentDidMount()更新的state值?
2) 如何运行函数 navigator.geolocation.getCurrentPosition() 来保存用户的当前位置并将其传递给 MapView,以便代码首先进行编译?
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = { latitude: null, longitude: null };
}
componentDidMount() {
navigator.geolocation.getCurrentPosition(position => {
this.setState({
latitude: position.coords.latitude,
longitude: position.coords.longitude,
});
});
}
render() {
return (
<View style={styles.container}>
<MapView
style={styles2.map}
initialRegion={{
latitude: this.state.latitude,
longitude: this.state.longitude,
latitudeDelta: 0.0922,
longitudeDelta: 0.0421,
}}
/>
{console.log(this.state.latitude)}
{console.log(this.state.longitude)}
</View>
);
}
}
最佳答案
只要您的组件通过 state
或 props 更新,React 就会重新渲染。在您的 componentDidMount()
中,您正在调用 setState()
,因此在此之后的某个时刻(因为它是异步的),您的组件将需要更新为新的 state
所以它再次呈现。
第一个 render()
发生在您的组件安装时。在这里您可以看到您所在州的 latitude
和 longitude
的初始值。
安装组件后,调用 setState()
将使用 latitude
和 longitude 的新值更新
所以你的组件将 state
render()
第二次你会看到 latitude
和 longitude
的新值。
编辑:
如果你想避免第一次显示 latitude
和 longitude
(注意。它仍然会渲染两次)你可以有条件地渲染,即
render() {
if(!this.state.longitude) {
return <View>Loading...</View>;
}
return (
<View style={styles.container}>
<MapView
style={styles2.map}
initialRegion={{
latitude: this.state.latitude,
longitude: this.state.longitude,
latitudeDelta: 0.0922,
longitudeDelta: 0.0421,
}}
/>
</View>
);
}
关于javascript - 为什么 render() 在 React Native 中被调用两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50082423/