Мне нужна помощь в исправлении ошибки в моем массиве списков - PullRequest
0 голосов
/ 30 апреля 2020

Я пишу код сообщества У меня есть ошибка в моей строке поиска. Приложение очень простое ... Каждый раз, когда пользователь создает имя, оно отображается в массиве списка. Моя проблема в том, что когда пользователь создает имя, имя которого не отображает мой список, но когда я ищу имя, оно показывает список.

Здесь видео, чтобы вы могли лучше понять https://www.youtube.com/watch?v=WIM-H4xXqMw

и код. Мне нужна помощь в панели поиска и отображения списка при нажатии кнопки

FolderHome.js - component

const [folder, emptyFolder] = useState([]);
const data = folder;

const [searchTerm, setSearchTerm] = useState("");
let [filteredData, setFilteredData] = useState(data);

//this function is when the user press the button we want to use the folderName(value) and display in a list.
//then when we add a foldername we update and add a new folder name.
//To understand I am just adding a folder name into my empty array. Now my array as a Folder inside.

const addFolder = (folderName) => {
    emptyFolder((currentFolder) => [
      ...currentFolder,
      { id: Math.random().toString(), value: folderName },
    ]);
  };

//Search
  const _searchFilterFunction = (event, data) => {
    let newData = [];
    setSearchTerm({ searchTerm: event });
    if (event) {
      newData = data.filter((item) => {
        const textData = event.toUpperCase();
        const nameFolder = item.value.toUpperCase();
        return nameFolder.includes(textData);
      });
      setFilteredData([...newData]);
    } else {
      setFilteredData([...data]);
    }
  };

return (
    <View style={styles.HomeContainer}>
      <TextInput
        underlineColorAndroid="transparent"
        autoCapitalize="none"
        placeholderTextColor="#9a73ef"
        style={styles.search}
        placeholder="Search"
        onChangeText={(value) => {
          _searchFilterFunction(value, data);
        }}
      />
      <FolderInput myFolder={addFolder} />

      {filteredData.map((item, index) => {
        return <Text key={item.id}>{item.value}</Text>;
      })}
    </View>
  );
};

FolderInput. js - Компонент

const FolderInput = (props) => {
  //This function we handle the input and output off Folder
  const [outputFolder, inputFolder] = useState("");

  //This arrow function is handling the folder name on onChangeText in TextInput
  const folderName = (entereName) => {
    inputFolder(entereName);
  };

  //Function to clear input when done enter folder name
  const clearInput = () => {
    props.myFolder(outputFolder);
    inputFolder("");
  };

  return (
    // TouchableWithoutFeedback allow to register a touche withou nothing happen to it
    <View style={styles.outputContainer}>
      <TouchableWithoutFeedback
        onPress={() => {
          Keyboard.dismiss();
        }}
      >
        <View style={styles.containerFolder}>
          <TextInput
            blurOnSubmit
            placeholder="Create Folder"
            style={styles.containerTextInput}
            onChangeText={folderName}
            //we pass the name folder into is value by biding and store into outputFolder
            value={outputFolder}
          />
          <TouchableOpacity>
            <AntDesign
              onPress={clearInput}
              name="addfolder"
              backgroundColor="black"
              size={30}
            />
          </TouchableOpacity>
        </View>
      </TouchableWithoutFeedback>
    </View>
  );
};

export default FolderInput;

Большое спасибо за всю вашу тяжелую работу заранее:)

1 Ответ

1 голос
/ 30 апреля 2020

Вы не должны иметь отфильтрованные данные в качестве состояния. это вычисляемый результат searchTerm и папки. просто объявите это как:

const filteredDate = folder.filter((item) => {
        const textData = searchTerm.toUpperCase();
        const nameFolder = item.value.toUpperCase();
        return nameFolder.includes(textData);
      });

Вы можете взглянуть на простую реализацию поиска в этой закуске: https://codesandbox.io/s/cocky-cori-n704s?file= / src / App. js

...