React Native: обновление FlatList не отображается, если оно истинно при первой загрузке - PullRequest
0 голосов
/ 12 мая 2018

Я столкнулся с проблемой, из-за которой мой индикатор обновления не показывает даже состояние, установленное в моем конструкторе.Но он отображается во время нажатия кнопки.

Ниже мой код

class ProductList extends Component {

  constructor(props){
    super(props);

    this.state = {
      productList: null,
      refreshing: true,
    }
  }

  async componentWillMount() {

  }

  async _handleRefresh() {
    console.log('test');
    this.setState({ refreshing: false });
  };

  render() {
    return (
      <View style={{ flex: 1, backgroundColor:'#EFEFF4' }}>    
        <View style={{ flexDirection:'row',backgroundColor:'#fff',borderBottomWidth:0.5,borderBottomColor:'#cbd2d9' }}>
          <Text style={{ padding:10, fontFamily:'open-sans-regular'  }}>{this.state.searchText}</Text>
          <TouchableOpacity style={{ marginLeft:'auto',padding:10 }} 
              onPress={() => this.setState({ refreshing: true }) }>
            <Text style={{ color:'#6391c0', fontFamily:'open-sans-regular' }}>Search</Text>
          </TouchableOpacity>
        </View>     
        <FlatList
          data={this.state. productList}
          renderItem={(item) => <CustomList navigation={this.props.navigation} data={item} />}
          keyExtractor={(item, index) => index}
           ={this.state.refreshing}
          onRefresh={() => this._handleRefresh()}
          ListEmptyComponent={() =>  
            <View style={{ flex:1, justifyContent:'center', alignItems:'center' }}>
              <Text style={{ marginTop: 150 }}>No records found, try search again!</Text>
            </View> 
          }
        />
      </View>
    );
  }
}

export default ProductList;

Этот компонент будет использоваться в моем компоненте React-Native-Tab-View, который находится ниже

import React, { Component } from 'react';
import { View , Text, StyleSheet, Dimensions } from 'react-native';
import MyProductList from '../profile/myProductList';
import { TabViewAnimated, TabBar } from 'react-native-tab-view';

class MyProduct extends Component {

    static navigationOptions = ({ navigation }) => ({
        headerTitle : 'My Product'
    });

    constructor(props){
        super(props);
        this.state = {
            index: 0,
            routes: [
              { key: 'upComing', title: 'Up coming' },
              { key: 'completed', title: 'Completed' },
            ],
          };
    }

    _handleIndexChange = index => this.setState({ index });

    _renderHeader = props => (
        <TabBar 
            indicatorStyle={{ backgroundColor:'#0079BF'}} 
            style={{ backgroundColor:'#FFFFFF' }} 
            tabStyle={{ padding:5 }}
            labelStyle={{ color:'black',fontWeight:'bold', fontSize:15, fontFamily:'open-sans-bold' }}
            getLabelText={({ route }) => route.title}
            {...props} />
    );

    _renderLabel = ({ route }) => (
        <Text>{route.title}</Text>
    );

    _renderScene = ({ route, focused }) => {
        switch (route.key) {
          case 'upComing': {
            return < ProductList focused={focused} navigation={this.props.navigation} />;
          }
          case 'completed':
            return < ProductList focused={focused} navigation={this.props.navigation} type={1} />;
          default:
            return null;
        }
    };  

    render() {
        return (
            <TabViewAnimated
                navigationState={this.state}
                renderScene={this._renderScene}
                renderHeader={this._renderHeader}
                onIndexChange={this._handleIndexChange}
                animationEnabled={false}
                swipeEnabled={false}
            />
        );
    }
}

export default MyProduct;

Индикатор обновления не отображается, даже если я установил состояние обновления в True в ProductList.Но если я нажму вручную от нажатия кнопки, он покажет.

Любая помощь приветствуется.

1 Ответ

0 голосов
/ 12 августа 2018

Может не сработать, потому что вы не реализуете обновление свойства.

<FlatList
    data={ this.props.productList }
    refreshing={ this.props.isLoading }
    onRefresh={ this._onHandleRefresh }
    renderItem={ ({item}) => this._renderListViewRow(item) }
    keyExtractor={ item => item.id } />

Еще один способ визуализации индикатора загрузки внутри flatlist - использование ListFooterComponent, который выглядит следующим образом:

<FlatList
    data={ this.props.productList }
    refreshing={ false }
    onRefresh={ this._onHandleRefresh }
    ListFooterComponent={ this._renderFooter }
    renderItem={ ({item}) => this._renderListViewRow(item) }
    keyExtractor={ item => item.id } />

и _renderFooter - это метод с простой логикой

_renderFooter() {
    if (!this.props.isLoading) return null;

    return (
        <View style={{ flex: 1, flexDirection: 'column', alignItems: 'center', justifyContent: 'center', paddingVertical: 10 }}>
            <ActivityIndicator animating size="small" />
        </View>
    );
}

В этом случае я использую избыточность, поэтому в основном у меня есть 3 различных состояния (запрос, успех и сбой)) .. и когда я запускаю «запрос», this.props.isLoading имеет значение true, а когда «успех» или «сбой», я изменяю this.props.isLoading на false.

кстати это использует React Native v0.53.0

...