【问题标题】:Trouble having filter method working for my flatList无法让过滤器方法适用于我的 flatList
【发布时间】:2020-12-14 17:35:11
【问题描述】:

我一直在尝试过滤掉用户输入的项目的名称,并告诉他们该项目已找到,如果该项目不存在,那么用户也应该被提醒,但我不知道由于某种原因,我的过滤方法似乎不起作用。这是我现在拥有的 flatList。

const data = [
  {
    groceryItem: 'Apple',
    price: '$2.99',
    category: 'Produce',
    src: require('./assets/apples.jpg'),
    id: Math.floor(Math.random() * 100) + 1
  },
  {
    groceryItem: 'Pear',
    price: '$2.49',
    category: 'Produce',
    src: require('./assets/pear.jpg'),
    id: Math.floor(Math.random() * 100) + 1
  }]

这是我在列表中搜索项目的代码。 NameInput 是用户输入,设置为用户输入的内容。

 const [nameInput, setNameInput] = useState('');
 const [itemsList, setItemsList] = useState(data); //storing data items temporarily

 const searchItem = () => {
    if (nameInput == "") {
      Alert.alert("At least an input is empty.");
    } 
    else if (itemsList.filter(itemFound)) {
      Alert.alert("Item " + nameInput + " has been found." + '\n' + 'You want to add it in the list?'+"\n"+"If, yes click on the modal below.");
    }
  };


function itemFound(item) {
  if (item.groceryItem == nameInput ) {
    return item;
  }else{
    Alert.alert(nameInput +" isn't available. Sorry!");
  }
} 

稍后,当单击按钮时,如果该项目存在或不在列表中,则应提醒用户。 我不知道让我的过滤器方法在这里工作我缺少什么。如果有人可以帮助我,那就太好了。 提前致谢!

【问题讨论】:

    标签: javascript reactjs react-native filter react-native-flatlist


    【解决方案1】:

    您不能在过滤器函数中返回 item。 它返回truefalse。 Filter 会自行返回一个新的(过滤后的)数组。

    尝试寻找这样的产品:

    const searchItem = () => {
        if (nameInput === "") {
            Alert.alert("At least an input is empty.");
        } 
        else if (itemFound()) {
            Alert.alert("Item " + nameInput + " has been found." + '\n' + 'You want to add it in the list?'+"\n"+"If, yes click on the modal below.");
        }
    };
    
    function itemFound() {
        for (let item of itemsList) {
            if (item.groceryItem === nameInput)
                return true;
        }
    
        return false;
    }
    

    【讨论】:

      【解决方案2】:

      如果您只想查看该项目是否在列表中,您可以使用Array.some 如果找到则返回 true,如果未找到则返回 false

      如果您想访问相关对象,您可以使用Array.find,它将返回该对象或undefinedArray.filter 将返回一个包含所有匹配对象的数组,find 将返回找到的第一个,所以这取决于你想要做什么

      const searchItem = () => {
          const itemFound = itemsList.some(item => item.groceryName === nameInput);
      
          if (nameInput == "") {
            Alert.alert("At least an input is empty.");
          } else if (itemFound) {
            Alert.alert("Item " + nameInput + " has been found." + '\n' + 'You want to add it in the list?'+"\n"+"If, yes click on the modal below.");
          } else {
            Alert.alert("not found..."
          }
        };
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-03-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-09
        • 1970-01-01
        • 1970-01-01
        • 2017-05-15
        相关资源
        最近更新 更多