自定义选项卡React Native避免重新渲染

时间:2018-11-12 00:34:22

标签: reactjs react-native

有没有一种方法,一旦您输入并单击另一个选项卡后返回,就不会重新呈现选项卡内容。事实是,当我转到另一个选项卡并返回时,总是重新渲染。我不知道解决方案是否可能与纯组件和shouldComponentUpdate有关,但我不知道以哪种方式使用它们 这是我的代码:

constructor() {
super();
this.state = {
  user: null,
  isLoaded: false,
  isLoadedMyPosts: false,
  tabSelected: 1,
  myPosts: [],
  favoritesPosts: []
}

}

componentWillMount() {
    storage.load({
      key: "user",
    }).then(userLocal => {
      //Para tener la ultima informacion en los contadores
      API.getUser(userLocal._id).then((data) => {
        this.setState({ user: data[1], isLoaded: true })
      })
      API.getPostsByUser(userLocal._id).then((data) => {
        this.setState({ myPosts: data, isLoadedMyPosts: true })
      })
    }).catch(err => {
      // leave user null
      this.setState({ isLoaded: true, isLoadedMyPosts: true })
      return;
    })
  }

changeTab(value) {
switch (value) {
  case 1:
    this.setState({ tabSelected: 1 })
    break;
  case 2:
    this.setState({ tabSelected: 2 })
    storage.load({
      key: "favorites",
    }).then(favs => {
      if (favs && favs.length) {
        this.setState({ favoritesPosts: favs });
      } else {
        this.setState({ favoritesPosts: null });
      }
    }).catch(err => {
      this.setState({ favoritesPosts: null });
      return;
    })
    break;
}

}

这是我渲染的重要部分

{!this.state.isLoadedMyPosts &&
          <View style={styles.loadingPosts}>
            <ActivityIndicator size="large" color="#F5DA49" />
          </View>
        }
        {this.state.isLoadedMyPosts && this.state.tabSelected === 1 &&
          //this.state.myPosts.map((item, index) => {
          // return (<PostItem key={item._id} item={item} isTabFavorites={false} />)
          // })
          <FlatList
            data={this.state.myPosts}
            renderItem={({ item, separators }) => (
              <PostItem key={item._id} item={item} isTabFavorites={false} />
            )}
            keyExtractor={item => item._id}
            onEndReachedThreshold={0.5}
          />
        }

        {this.state.isLoadedMyPosts && this.state.myPosts.length === 0 &&
          <View style={styles.noPosts}>
            <Icon name="md-alert" size={40} />
            <Text style={styles.textNoPosts}> {!this.state.user ? "Necesitas iniciar sesión" : "No tienes públicaciones"}</Text>
          </View>
        }

        {this.state.isLoadedMyPosts && this.state.tabSelected === 2 && this.state.favoritesPosts &&
          this.state.favoritesPosts.map((item, index) => {
            return (<PostItem key={item._id} item={item} isTabFavorites={true} removedFav={this.removedFav.bind(this)} />)
          })}

        {this.state.isLoadedMyPosts && !this.state.favoritesPosts && this.state.tabSelected === 2 &&
          <View style={styles.noPosts}>
            <Icon name="md-alert" size={40} />
            <Text style={styles.textNoPosts}> No tienes favoritos</Text>
          </View>
        }

0 个答案:

没有答案