为什么在 ReactNative 中 render() 被调用两次?

Sar*_*wal 2 javascript reactjs react-native

我目前正在尝试使用一个屏幕制作一个应用程序,其中屏幕的背景由以用户当前坐标为中心的地图占据。在下面的代码中,我在 App 类组件的状态中将经度和经度保存为 null。然后,我使用继承的方法“componentDidMount()”更新用户当前位置的状态,最后在 render() 中我使用 this.state.latitude 和 this.state.longitude 来通知纬度和经度的值地图视图。

代码无法编译。使用console.log,我将问题隔离为render() 被调用两次,我的console.log 语句首先将空值输出到控制台,然后输出用户的当前位置。

所以两个问题。

1)为什么console.log会向控制台输出两次不同的值,一次是传入的状态值,一次是componentDidMount()更新的状态值?

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>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

Ant*_*ony 8

每当您的组件通过state或 props更新时,React 都会重新渲染。在您componentDidMount()正在调用setState(),因此在此之后的某个时间点(因为它是异步的),您的组件将需要为新组件进行更新,state以便再次呈现。

第一个render()发生在您的组件安装时。在这里,您将看到状态的初始值latitudelongitude状态。

你的组件已经安装后,你的通话setState()将更新state与新价值latitude,并longitude让你的组件将render()第二次在这里您将看到的新的价值观latitudelongitude

编辑:

如果你想避免latitudelongitude(注意。它仍然会渲染两次)的第一次显示,你可以有条件地渲染即

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>
    );
}
Run Code Online (Sandbox Code Playgroud)