首页 > 解决方案 > React Hook 搜索输入过滤器 | 当我更新我的项目对象数组时,useEffect 不会重新加载项目

问题描述

每个人!

我有点锁定,在 React Hook 输入搜索过滤字段的实现。

我有一个对象数组,当我更新它时,我定义的过滤器不会更新并产生它不起作用的错觉,但是在搜索输入中输入一个单词后它会起作用,我无法更新该项目列表。

我是反应钩子的新手,我不明白如何更新这个字段,以便它最终对我有用。

你能帮我个忙吗

export function HomeScreen({ navigation }) {
  const userData = useContext(UserContext);
  const dataDelivery = userData.dataDelivery.filter(re => re.task_status === 'Pendiente')
  const [searchTerm, setSearchTerm] = React.useState("");
  const [searchResults, setSearchResults] = React.useState(dataDelivery);

  React.useEffect(() => {
    const results = dataDelivery.filter(delivery => (
      // delivery.id.includes(searchTerm) ||
      delivery.firstname.toLowerCase().includes(searchTerm.toLowerCase()) ||
      delivery.lastname.toLowerCase().includes(searchTerm.toLowerCase()) ||
      String(delivery.document).includes(searchTerm) ||
      String(delivery.door).includes(searchTerm) ||
      delivery.street.toLowerCase().includes(searchTerm.toLowerCase())
    ));
    console.log(results.length)
    setSearchResults(results);
    
  }, [searchTerm]);

  return (
    <View style={styles.container}>
      <HeaderBar navigation={navigation} />

      <View style={[styles.updateIcon]}>
        <Text style={{ color: '#fff', fontSize: 20, alignSelf: 'center', marginVertical: 10 }}> Hola {userData.firstname}! </Text>
        {/* <Feather name="refresh-ccw" size={50} color="#fff" /> */}
        <Text style={{ color: '#eee', fontSize: 20 }}>TENES {dataDelivery.length} CUPOS DE ALIMENTOS</Text>
        <Text style={{ color: '#eee', fontSize: 20 }}><Text style={{ color: '#eee', fontSize: 20, fontStyle: 'italic', fontWeight: '700' }}>pendientes</Text> POR REPARTIR </Text>
        <SearchFilterBox value={searchTerm} handleChange={text => setSearchTerm(text)} />
      </View>

      {/* {searchResults.map(delivery => (
        <DeliveryBox item={delivery} />
      ))} */}

      <DeliveryBox dataset={searchResults} />
    </View>
  );
}

export function DeliveryBox({ dataset }) {
    // console.log('dataset de items:',dataset)
    const handlePersonEntityDelivery = async () => new Promise((resolve) => {
        Alert.alert(
            "Iniciar entrega : Paso 1",
            "Seleccione el destinatario de la entrega",
            [
                {
                    text: "Titular",
                    onPress: () => resolve('Titular')

                },
                {
                    text: "No Titular/Familiar",
                    onPress: () => resolve('No Titular/Familiar')
                },
                // {
                //     text: "Institución",
                //     onPress: () => resolve('Institucion')
                // },
                {
                    text: "Cancelar",
                    onPress: () => resolve('Salir')
                }
            ],
            { cancelable: false }
        );
    });
    const handleItHasDocument = async () => new Promise((resolve) => {
        Alert.alert(
            "Iniciar entrega : Paso 2",
            "Seleccione Si posee o no documento",
            [
                {
                    text: "Escanear DNI",
                    onPress: () => resolve(true)
                },
                {
                    text: "Sin DNI",
                    onPress: () => resolve(false)
                },
                {
                    text: "Cancelar",
                    onPress: () => resolve('Salir')
                }
            ],
            { cancelable: false }
        );
    });

    const handleSelectedDelivery = async (item) => {
        const person_entity = await handlePersonEntityDelivery();
        
        if(person_entity === 'Salir' || hasDocument === 'Salir')
            return;

        const hasDocument = await handleItHasDocument();
        
        if(hasDocument === 'Salir' || hasDocument === 'Salir')
            return;

        hasDocument
            ? RootNavigation.navigate('Barcode', { ...item, hasDocument, person_entity })
            : RootNavigation.navigate('Camara', { ...item, delivery_detail:{}, hasDocument, person_entity })
    }
    
    const renderItemDelivery = ({ item }) => (
        <View style={styles.container}>
            <View style={styles.card}>
                <TouchableOpacity
                    onPress={() => (Alert.prompt("Asignar Número de bolsa", "Indicar un ID"))}
                >
                    <Image source={require('../assets/box_icon.png')} style={{ width: 50, height: 50, borderRadius: 10 }} />
                    <Text style={styles.boxId}>ID:{item.id}</Text>
                </TouchableOpacity>
                <View style={{ flex: 1, flexDirection: 'column', paddingLeft: 10 }}>
                    <Text>Titular: {item.firstname} {item.lastname}</Text>
                    <Text>Domicilio: {item.street} {item.door}</Text>
                    <Text>DNI: {item.document}</Text>
                </View>
                <TouchableOpacity style={{ alignItems: 'center' }} onPress={() => (handleSelectedDelivery(item))}>
                    <Entypo name={'hand'} size={30} color='#4A8FC7' />
                    <Text style={{ alignSelf: 'flex-end' }}>Entregar</Text>
                </TouchableOpacity>
            </View>
        </View>
    )


    return (
        <FlatList
            scrollEnabled
            data={dataset}
            renderItem={renderItemDelivery}
            keyExtractor={item => item.id}
        />
    );

}

谢谢你

标签: javascriptreactjsreact-hooks

解决方案


推荐阅读