React-native 渲染方法 运行 加载两次

React-native render method running twice on load

我到处都在寻找合适的解决方案,但找不到!当我打开我的模拟器时,当我的应用程序加载后,它会运行渲染方法两次。这意味着我只能从我的 redux-store 中获得 InitialState

这是我的启动脚本:

"scripts": {
    "android-setup-port": "adb reverse tcp:8081 tcp:8080",
    "start": "env NODE_ENV=DEV rnws start --hostname localhost",
    "build": "env NODE_ENV=PRODUCTION rnws bundle",
    "test": "eslint src",
    "debugger-replace": "remotedev-debugger-replace --hostname localhost --port 5678",
    "remotedev": "npm run debugger-replace && remotedev --hostname localhost --port 5678"
  },

这是我的布局:

  componentWillMount() {
    this.props.actions.fetchalbum("1");
  }

  render() {
    var album = this.props.album;

    console.log("\n\nlayout_____", album); // THIS IS PRINTED OUT TWICE

    // Create the feed
    var albumObj = [];

    for (var i = 0; i < album.albums.length; i++) {
      feedObj.push(
        <View key={i}>
          <AlbumComp post={ album.albums[i] }/>
        </View>
      );
    }

    return (  
      <ScrollView>
        { albumObj }
      </ScrollView>
    )
  }
};

当我打开应用程序时,它 console.logs 相册处于初始状态,然后又是使用 fetch 方法从 API 检索到的新状态。

有什么办法可以解决这个问题吗?

应用程序的行为与它应有的完全一致 - 它在安装组件时呈现一次,然后在异步调用再次更新状态后再次呈现。

您无法阻止应用程序根组件的初始呈现。但是,您可以做的是通过例如处理渲染方法中的未加载状态在加载数据之前显示加载微调器。也许是这样的:

render() {
  var album = this.props.album;
  if (!album) {
    return <ActivityIndicatorIOS />;
  }

  console.log("\n\nlayout_____", album);

  //...
}