Функции SearchBar и Read / Unread не работают вместе - React Native - PullRequest
0 голосов
/ 20 апреля 2020

У меня есть простой FlatList, отображающий 2 элемента в HomeComponent. Элементы отображаются в компоненте элемента. Я добавил функцию чтения / непрочитания со значком, используя два состояния -> messagesRead и selectedNotificationList []. Мой лог c работает здесь. Когда я нажимаю на элемент, значок исчезает.

У меня также есть панель поиска, которая ищет описание. Логика c поиска работает, когда оба элемента Непрочитанные . Но когда один из элементов или оба элемента имеют значение Read , тогда я выполняю поиск в любом тексте, значок вновь появляется.

Мой код указан ниже:

Дом:

import Item from './Item';

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


  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,
        temp: responseJson,
    })
    })
  };

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

  setNotifRead(bool){
    this.setState({ notificationRead: bool });
    console.log('Read status is set to:', bool);
  }

  setReadCount(Id) {
    this.setState({ list: [...this.state.list, Id] });
    console.log('Read count is:', Id);
  }

  renderItem({item}) {
    return <Item item={item} 
    onPress = {()=> {this.goToDetails();this.setNotifRead(true)}}
    notificationRead={this.state.notificationRead}
    readNotifCountFn={(Id)=>{this.setReadCount(Id)}}
    />
  }  


  handleSearch(text){
      const newData = _.filter(this.state.temp, (item) => {
      const itemData = item.Desc ? item.Desc.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>
  );
  }


}

Предмет:

export default class Item extends Component {
  constructor(props){
    super(props)
      this.state = {
        selectedNotificationList: []
      }
  };

  handlePress () {
    return this.props.onPress();
  }

  setList(Id) {
    if(!this.state.selectedNotificationList.includes(Id)) {
    this.setState({
      selectedNotificationList: [...this.state.selectedNotificationList, Id]
    });
    console.log('List is set:',Id);
    return this.props.readNotifCountFn(Id);
  }
 }

  render() {
      const {row, badge, textContainer, id, ordername, desc, seperator} = styles;
      const { item, notificationRead } = this.props;
      const { selectedNotificationList } = this.state;
      const { Id, OrderName, Desc } = item;

          return (
              <View>
                <TouchableOpacity onPress={()=>{this.handlePress(); this.setList(Id)}} >
                     <View style={seperator}></View>
                    <View style={row}>
                     {
                      notificationRead === false || selectedNotificationList.includes(Id) === false ?
                        <View style={badge}>
                           <Badge status="error" containerStyle={{ padding:8, position:'absolute'}} />
                        </View> : null
                     } 
                      <View style={textContainer}>
                      <Text style={id}> {Id} </Text>
                      <Text style={ordername}> {OrderName} </Text>
                      <Text style={desc}> {Desc} </Text>
                      </View>
                    <View style={seperator}></View> 
                     </View>           
                 </TouchableOpacity>
              </View>
            )
}
}

Пожалуйста, помогите мне исправить мой код или сообщите мне лучший способ сделать это ??

...