【问题标题】:How to search FlatList in React Native using search bar and Redux Hooks如何使用搜索栏和 Redux Hooks 在 React Native 中搜索 FlatList
【发布时间】:2020-04-09 14:25:56
【问题描述】:

我正在尝试使用 react-native-dynamic-searchbar 和 Redux 挂钩在 React Native 中搜索 FlatList。有很多关于如何做到这一点的信息,但没有使用调度钩子。

我的非工作代码如下:

const Contacts = () => {
  const dispatch = useDispatch();
  const contacts = useSelector(state => state.user.parsedContacts);

  const renderContacts = contacts => {
    return (
      <ContactListItem
        name={contacts.item.full_name}
        phone={contacts.item.phone}
        isRegisteredUser={contacts.item.id !== 0 ? true : false}
      />
    )
  }

  const handleFilter = input => {
    dispatch(updateParsedContacts(contacts.filter(contact => contact.full_name.includes(input))));
  }

  if (contacts !== null) {
    return (
      <View>
        <StatusBar />
        <View style={styles.topMargin}>
        </View>
        <View style={styles.header}>
          <SearchBar
            iconColor="#EE578D"
            placeholder="Search Here..."
            onChangeText={handleFilter}
          />
        </View>
        <FlatList
          data={contacts}
          renderItem={renderContacts}
          initialNumToRender={5}
          maxToRenderPerBatch={10}
          windowSize={10}
          keyExtractor={(_, index) => index.toString()}
        />

当用户在搜索栏中输入文本时,我正在尝试实时更新 FlatList。 handleFilter 函数接收输入文本,但 Redux 存储没有正确更新。这应该如何实现?

【问题讨论】:

    标签: reactjs react-native react-redux


    【解决方案1】:

    你的代码有问题:

    搜索后,您会更新主要数据列表,因此,当您再次研究时,您会在过滤后的列表中进行搜索。如果您删除搜索字符,您将无法返回所有结果。

    为避免这种情况,我建议您为过滤后的合约添加一个新的子状态,或者在您的组件级别完成过滤:

    const contacts = useSelector(state => state.user.parsedContacts);
    
    // memoize a filtered contracts that is recalculated when either contracts of the input change
    const filteredContracts = React.useMemo(() => {
      return contracts.filter(contact => contact.full_name.includes(input));
    }, [contracts, input]);
    
    
    // ... later
            <FlatList
              data={filteredContracts}
              renderItem={renderContacts}
              initialNumToRender={5}
              maxToRenderPerBatch={10}
              windowSize={10}
              keyExtractor={(_, index) => index.toString()}
            />
    
    

    【讨论】:

      猜你喜欢
      • 2019-11-26
      • 1970-01-01
      • 1970-01-01
      • 2018-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-22
      相关资源
      最近更新 更多