Фильтр поиска неправильно отображает FlatList - PullRequest
1 голос
/ 17 апреля 2020

В моем flatList отображается 2 элемента, и если я ищу текст, он отображает этот элемент. Но теперь, когда я начинаю нажимать клавишу «Backspace» и удаляю текст поиска, остальные мои элементы не отображаются, а остаются на предыдущем элементе.

Мой код ниже:

export default class HomeComponent extends Component {
  constructor(props){
    super(props)
      this.state = {
        isLoading: true,
        notifications: [],
        query: ''
      }
  };


  componentDidMount() {
    fetch('https://140xya6a67.execute-api.ap-southeast-1.amazonaws.com/dev/', {
    method: 'GET',
  })
    .then((response) => response.json())
    .then((responseJson) => {
      this.setState({
        isLoading: false,
        notifications: responseJson,
        notificationRead: false
    })
    })
  };

  goToDetails() {
    return this.props.navigation.navigate(Details) ;
  }  


  renderItem({item}) {
    return <NotificationItem item={item} 
    onPress = {()=> {this.goToDetails()}}
    />
  }  


  handleSearch(text){
      const newData = _.filter(this.state.notifications, (item) => {
      const itemData = item.OrderDate ? item.OrderDate.toUpperCase() : ''.toUpperCase();
      const textData = text.toUpperCase();
      return itemData.indexOf(textData) > -1;
    });
    this.setState({
      notifications: newData,
      query:text,
    });
  }

  renderContent() {
    let {notifications} = this.state;

    return (
    <View>
    <SearchBar placeholder='type here...' lightTheme round value={this.state.query} onChangeText={(text)=>{this.handleSearch(text)}} />
    <FlatList
    keyExtractor={(item, id) => item.id} 
    data={notifications}
    renderItem={this.renderItem.bind(this)}
    /> 
    </View>

    );
  }


  render () {
  let {fill, container} = styles;

  return (
    <View style={ [fill, container] }>
      {this.renderContent()}
    </View>
  );
  }


}

Фильтр поиска работает, но как только я начинаю очищать текст поиска, мой плоский список должен перерисоваться в исходное состояние. Пожалуйста, проверьте мой код и дайте мне знать, что происходит не так.

1 Ответ

0 голосов
/ 17 апреля 2020

Проблема в том, что когда вы фильтруете свой список, вы теряете свои элементы из первоначального полного списка. Решение состоит в том, чтобы объявить 2 переменные в состоянии: 1, чтобы сохранить весь ваш элемент, а 2 других отфильтровать ваш поиск

export default class HomeComponent extends Component {
  constructor(props){
    super(props)
      this.state = {
        isLoading: true,
        allNotifications: [],
        filteredNotifications: [],
        query: ''
      }
  };


  componentDidMount() {
    fetch('https://140xya6a67.execute-api.ap-southeast-1.amazonaws.com/dev/', {
    method: 'GET',
  })
    .then((response) => response.json())
    .then((responseJson) => {
      this.setState({
        isLoading: false,
        allNotifications: responseJson,
        filteredNotifications: responseJson,
        notificationRead: false
    })
    })
  };

  goToDetails() {
    return this.props.navigation.navigate(Details) ;
  }  


  renderItem({item}) {
    return <NotificationItem item={item} 
    onPress = {()=> {this.goToDetails()}}
    />
  }  


  handleSearch(text){
      const newData = _.filter(this.state.allNotifications, (item) => {
      const itemData = item.OrderDate ? item.OrderDate.toUpperCase() : ''.toUpperCase();
      const textData = text.toUpperCase();
      return itemData.indexOf(textData) > -1;
    });
    this.setState({
      filteredNotifications: newData,
      query:text,
    });
  }

  renderContent() {
    let {filteredNotifications} = this.state;

    return (
    <View>
    <SearchBar placeholder='type here...' lightTheme round value={this.state.query} onChangeText={(text)=>{this.handleSearch(text)}} />
    <FlatList
    keyExtractor={(item, id) => item.id} 
    data={filteredNotifications}
    renderItem={this.renderItem.bind(this)}
    /> 
    </View>

    );
  }


  render () {
  let {fill, container} = styles;

  return (
    <View style={ [fill, container] }>
      {this.renderContent()}
    </View>
  );
  }


}
...