需要在React Native中根据复选框值过滤数组吗?

roqulrg3  于 2023-05-07  发布在  React
关注(0)|答案(1)|浏览(146)

基本上,我有一个由多个复选框组成的Modal,当我选中它们时,值可以轻松地输入到一个名为:checkedValues,该数组将被设置为名为:setNewArray和基于setNewArray中的值的flatlist正在显示,但现在我希望如果用户未选中复选框,则应从checkedValues数组中删除特定的未选中值,并更新setNewArray,然后flatlist相应地显示结果:

import React, {useState, useEffect} from 'react';
import {
  View,
  Text,
  Image,
  StyleSheet,
  TextInput,
  TouchableOpacity,
  TouchableWithoutFeedback,
} from 'react-native';

import {Search} from 'react-native-feather';

import SearchItem from './src/Screens/SearchItem';

import {getHeight, getWidth} from './src/Components/CommonFunctions';

//import {Modal} from 'react-native/Libraries/Modal/Modal';
import CheckBox from '@react-native-community/checkbox';

import Modal from 'react-native-modal';
import {
  widthPercentageToDP as wp,
  heightPercentageToDP as hp,
} from 'react-native-responsive-screen';

var checkedValues: any = [];

const FullfillmentScreen = ({route}) => {
  const {data} = route.params;
  const [currentDate, setCurrentDate] = useState<string>('');

  useEffect(() => {
    var date = new Date().getDate();
    var month = new Date().getMonth() + 1;
    var year = new Date().getFullYear();
    var hour = new Date().getHours();
    var min = new Date().getMinutes();
    setCurrentDate(date + ' ' + month + ' ' + year + ', ' + hour + ':' + min);
  }, []);
  //   console.log(data);
  const array: any = [
    {
      id: '1',
      state: 'Created',
      date: 'Over Due',
      // image: require('../Assets/fonts/chegg.png'),
      packageNumber: 'PKGX-128788868-17HJGJG',
      name: 'muqsit Chowhan',
      delivery: 'Next Day',
      val: 'VAS',
    },
    {
      id: '2',
      state: 'Created',
      date: [currentDate],

      packageNumber: 'PKGX-128788868-17HJGJG',
      name: 'Ali',
      delivery: 'Next Day',
      val: 'VAS',
    },
    {
      id: '3',
      state: 'Processing',
      date: [currentDate],
      // image: require('../Assets/fonts/chegg.png'),
      packageNumber: 'PKGX-128788868-17HJGJG',
      name: 'Chowhan',
      delivery: 'Next Day',
      val: 'VAS',
    },
    {
      id: '4',
      state: 'Picked',
      date: [currentDate],
      // image: require('../Assets/fonts/chegg.png'),
      packageNumber: 'PKGX-128788868-17HJGJG',
      name: 'Jamie',
      delivery: 'Next Day',
      val: 'VAS',
    },
    {
      id: '5',
      state: 'Packed',
      date: [currentDate],
      // image: require('../Assets/fonts/chegg.png'),
      packageNumber: 'PKGX-128788868-17HJGJG',
      name: 'qasim',
      delivery: 'Next Day',
      val: 'VAS',
    },
    {
      id: '6',
      state: 'Created',
      date: [currentDate],
      // image: require('../Assets/fonts/chegg.png'),
      packageNumber: 'PKGX-128788868-17HJGJG',
      name: 'abdullah',
      delivery: 'Next Day',
      val: 'VAS',
    },
    {
      id: '7',
      state: 'Created',
      date: [currentDate],
      // image: require('../Assets/fonts/chegg.png'),
      packageNumber: 'PKGX-128788868-17HJGJG',
      name: 'kamran',
      delivery: 'Next Day',
      val: 'VAS',
    },
    {
      id: '8',
      state: 'Created',
      date: [currentDate],
      // image: require('../Assets/fonts/chegg.png'),
      packageNumber: 'PKGX-128788868-17HJGJG',
      name: 'hamza',
      delivery: 'Next Day',
      val: 'VAS',
    },
  ];
  const [search, setSearch] = useState('');
  const [apply, setApply] = useState<boolean>(false);
  const [modalVisibile, setModalVisibile] = useState<boolean>(false);
  const [new_Array, setNewArray] = useState<string>([]);
  // const [isCreated, setIsCreated] = useState<any>(false);
  // const [isProcessing, setIsProcessing] = useState<any>(false);
  const [isChecked, setIsChecked] = useState<any>({
    created: false,
    processing: false,
    picked: false,
    packed: false,
    completed: false,
    cancelled: false,
  });
  //const[isPicked,setIsPicked]=useState(false)

  const options = [
    'Created',
    'processing',
    'Picked',
    'Packed',
    'Completed',
    'Cancelled',
  ];
  console.log('=====================NEW VALUES=====================');

***************************MAIN LOGIC IMPLEMENTATION(Incorrect)**************************************

  const filtered = (type: any) => {
    if (isChecked.created === false) {
      //var newCheckedValues = checkedValues.replace('Created', ' ');
      //checkedValues = newCheckedValues;
      var newCheckedValues = checkedValues.filter(
        (item: any) => item !== 'Created',
      );
      console.log('newCheckedValues======>', newCheckedValues);
      setNewArray(newCheckedValues);
    }
    checkedValues.push(type);
    console.log('Checked Values Array====>', checkedValues);
    //console.log('Array========>', array);
    setNewArray(
      array.filter((item: any) => {
        return checkedValues.includes(item.state);
      }),
    );

  
  };
******************************************************************************************

***************************MAIN LOGIC IMPLEMENTATION(Correct)**************************************
 const filtered = (type: any) => {
    if (checkedValues?.includes(type)) {
      checkedValues = checkedValues.filter((item: any) => item !== type);
      setNewArray(checkedValues);
    } else {
      checkedValues.push(type);
      console.log('Didnot entered in if');
    }
    setNewArray(
      array.filter((item: any) => {
        return checkedValues.includes(item.state);
      }),
    );
    
  };
******************************************************************************************

 
  console.log('NewArray State======>', new_Array);

  console.log('Is Checked StateValue========>', isChecked);
return (
    <View style={{flex: 1, height: '100%'}}>
      <View style={styles.main}>
        <View style={styles.orgNameView}>
          <Text style={styles.orgData}>{data}</Text>
        </View>
        <View>
          <Text style={styles.fullfillmentText}>Fulfillments</Text>
        </View>
        <TouchableOpacity
          onPress={() => setModalVisibile(true)}
          style={styles.filterView}>
          <Image
            source={require('./src/Assets/fonts/levels.png')}
            style={styles.filterIcon}
          />
        </TouchableOpacity>
      </View>
      <View style={styles.container}>
        <View style={styles.textInput}>
          <Search size={30} color="#808080" style={styles.search} />
          <TextInput
            placeholder="Type to Search"
            value={search}
            onChangeText={query => setSearch(query)}
          />
        </View>
      </View>
      <View style={{height: '80%'}}>
        <SearchItem
          data={array}
          search={search}
          setSearch={setSearch}
          isChecked={isChecked}
          data2={new_Array}
          setApply={setApply}
        />
      </View>
      <TouchableWithoutFeedback>
        <Modal isVisible={modalVisibile} style={styles.modal}>
          <TouchableWithoutFeedback onPress={() => setModalVisibile(false)}>
            <View style={styles.modalView}>
              <View
                style={{
                  justifyContent: 'flex-start',
                  alignItems: 'center',
                  // borderWidth: 1,
                  // borderColor: 'black',
                  paddingVertical: 5,
                }}>
                <Text style={styles.topBar} />
              </View>
              <View style={styles.filterHeadingView}>
                <Text style={styles.filterText}>Filters</Text>
                <TouchableOpacity
                  onPress={() => {
                    //setIsCreated(false);
                    setNewArray([]);
                    //setIsProcessing(false);
                    setIsChecked(false);
                    checkedValues = [];
                    console.log(
                      'Checked Value Array after clear:===>',
                      checkedValues,
                    );
                  }}>
                  <Text style={styles.clearText}>Clear</Text>
                </TouchableOpacity>
              </View>
              <View style={styles.statusView}>
                <Text style={styles.statusText}>Status</Text>
              </View>
              <View style={styles.checkboxView}>
                <Text style={styles.checkItems}>{options[0]}</Text>
                <CheckBox
                  style={styles.checkbox}
                  disabled={false}
                  value={isChecked.created}
                  onValueChange={newValue => {
                    setIsChecked({...isChecked, created: newValue});
                    filtered('Created');
                  }}
                />
              </View>
              <View style={styles.checkboxView}>
                <Text style={styles.checkItems}>{options[1]}</Text>
                <CheckBox
                  style={styles.checkbox}
                  disabled={false}
                  value={isChecked.processing}
                  onValueChange={newValue => {
                    setIsChecked({...isChecked, processing: newValue});
                    filtered('Processing');
                  }}
                />
              </View>
              <View style={styles.checkboxView}>
                <Text style={styles.checkItems}>{options[2]}</Text>
                <CheckBox
                  style={styles.checkbox}
                  disabled={false}
                  value={isChecked.picked}
                  onValueChange={newValue => {
                    setIsChecked({...isChecked, picked: newValue});
                    filtered('Picked');
                  }}
                />
              </View>
              <View style={styles.checkboxView}>
                <Text style={styles.checkItems}>{options[3]}</Text>
                <CheckBox
                  style={styles.checkbox}
                  disabled={false}
                  value={isChecked.packed}
                  onValueChange={newValue => {
                    setIsChecked({...isChecked, packed: newValue});
                    filtered('Packed');
                  }}
                />
              </View>
              <View style={styles.checkboxView}>
                <Text style={styles.checkItems}>{options[4]}</Text>
                <CheckBox
                  style={styles.checkbox}
                  disabled={false}
                  value={isChecked.completed}
                  onValueChange={newValue =>
                    setIsChecked({...isChecked, completed: newValue})
                  }
                />
              </View>
              <View style={{flex: 1, height: getHeight(100)}}>
                <View style={styles.checkboxView}>
                  <Text style={styles.checkItems}>{options[5]}</Text>
                  <CheckBox
                    style={styles.checkbox}
                    disabled={false}
                    value={isChecked.cancelled}
                    onValueChange={newValue =>
                      setIsChecked({...isChecked, cancelled: newValue})
                    }
                  />
                </View>
              </View>
              <View style={styles.applyButtonView}>
                <TouchableOpacity
                  style={styles.buttonApply}
                  onPress={() => {
                    setModalVisibile(false);
                    setApply(true);
                  }}>
                  <Text style={styles.buttonText}>Apply</Text>
                </TouchableOpacity>
              </View>
            </View>
          </TouchableWithoutFeedback>
        </Modal>
      </TouchableWithoutFeedback>

我尝试了基于复选框的布尔值的过滤方法。虽然控制台值仍然是好的,但无论您是否选中该值,它都会被添加到checkedValues数组中。

fdbelqdn

fdbelqdn1#

基于您提供的代码片段,您可以使用以下代码

const updateSelectedItems = selected => {
    const checkedValues = new_Array ?? [];

    const exist = _.findIndex(checkedValues, item => item === selected);

    if (exist > -1) {
      //exist in checkedValues remove from both arrays
      checkedValues.splice(exist, 1);
    } else {
      checkedValues.push(selected);
    }
    setNewArray([...checkedValues]);
  };

这里的'selected'是作为一个字符串使用的,如果你需要一个对象,那么你可以根据你的需要改变它
如果你需要进一步帮助请告诉我。

相关问题