javascript - 为什么 render() 在 React Native 中被调用两次?

标签 javascript reactjs react-native

我目前正在尝试制作一个只有一个屏幕的应用程序,其中屏幕背景由以用户当前坐标为中心的 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() 发生在您的组件安装时。在这里您可以看到您所在州的 latitudelongitude 的初始值。

安装组件后,调用 setState() 将使用 latitudelongitude 的新值更新 state 所以你的组件将 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>
    );
}

关于javascript - 为什么 render() 在 React Native 中被调用两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50082423/

相关文章:

javascript - 从值中获取 JSON 键或反转 JSON 数据

javascript - 基于子组件在 <App/> 级别更改 React 状态的最佳方法

reactjs - Hooks 中的 this[field] 替代方案

android - react native Android : Manifest merger failed

javascript - 无法在 AngularJS 选择框上设置默认值

javascript - 在多个部分中鼠标悬停

javascript - 如何在react-native中导出所有项目的const

javascript - javascript中如何将多个对象转换为键值对的Array[]

javascript - 为什么 javascript 报告 Motorola Atrix MB860 4G 的宽度为 800px?不应该是540px吗

reactjs - 用于 React 和 React Native 的可插入跨平台软件设计