React Native Hooks 搜索过滤器 FlatList [英] React Native Hooks Search Filter FlatList

查看:76
本文介绍了React Native Hooks 搜索过滤器 FlatList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作 Covid19 React Native Expo 应用程序.它包含一个搜索过滤器,用户可以从中选择一个国家,然后将向用户显示所选国家的结果.我在我的 Android 设备上不断收到此错误意外的标识符你";在 web pack 上,国家/地区会加载,但无法正确过滤.

I am trying to make a Covid19 React Native Expo app. It contains a search filter from which user will select a country then the selected country results will be shown to the user. I keep getting this error on my Android device "Unexpected Identifier You" while on web pack the countries load but they don't filter correctly.

工作零食链接:https://snack.expo.io/@moeez71/ac5758

这是我的代码:

import React, { useState, useEffect } from "react";
import {
  ActivityIndicator,
  Alert,
  FlatList,
  Text,
  StyleSheet,
  View,
  TextInput,
} from "react-native";

export default function ABCDEE() {
  const [arrayholder, setArrayholder] = useState([]);
  const [text, setText] = useState("");
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(true);

  const fetchAPI = () => {
    return fetch("https://api.covid19api.com/countries")
      .then((response) => response.json())
      .then((responseJson) => {
        setData(responseJson);
        setLoading(false);
        setArrayholder(responseJson);
      })
      .catch((error) => {
        console.error(error);
      });
  };

  useEffect(() => {
    fetchAPI();
  });

  const searchData = (text) => {
    const newData = arrayholder.filter((item) => {
      const itemData = item.Country.toUpperCase();
      const textData = text.toUpperCase();
      return itemData.indexOf(textData) > -1;
    });

    setData(newData);
    setText(text);
  };

  const itemSeparator = () => {
    return (
      <View
        style={{
          height: 0.5,
          width: "100%",
          backgroundColor: "#000",
        }}
      />
    );
  };

  return (
    <View>
      {loading === false ? (
        <View style={styles.MainContainer}>
          <TextInput
            style={styles.textInput}
            onChangeText={(text) => searchData(text)}
            value={text}
            underlineColorAndroid="transparent"
            placeholder="Search Here"
          />

          <FlatList
            data={data}
            keyExtractor={(item, index) => index.toString()}
            ItemSeparatorComponent={itemSeparator}
            renderItem={({ item }) => (
              <Text style={styles.row}>{item.Country}</Text>
            )}
            style={{ marginTop: 10 }}
          />
        </View>
      ) : (
        <Text>loading</Text>
      )}
    </View>
  );
}

const styles = StyleSheet.create({
  MainContainer: {
    paddingTop: 50,
    justifyContent: "center",
    flex: 1,
    margin: 5,
  },

  row: {
    fontSize: 18,
    padding: 12,
  },

  textInput: {
    textAlign: "center",
    height: 42,
    borderWidth: 1,
    borderColor: "#009688",
    borderRadius: 8,
    backgroundColor: "#FFFF",
  },
});

推荐答案

你在上面的代码中犯了两个错误

You had made two mistakes in the above code

  1. useEffect 第二个参数应该是一个空数组,因为它充当 componentDidMount()

useEffect(() => {fetchAPI();},[])

在FlatList renderItem 中需要解构item.

in FlatList renderItem need to destructure the item.

  renderItem={( {item}  ) => <Text style={styles.row}
   >{item.Country}</Text>}

工作代码

    import React, {useState, useEffect} from "react"
import { ActivityIndicator, Alert, FlatList, Text, StyleSheet, View, TextInput } from 'react-native';

export default function ABCDEE(){


  const [arrayholder,setArrayholder] =useState([])
  const[text, setText] = useState('')
  const[data, setData] = useState([])
  const [loading , setLoading] = useState(true)

  const fetchAPI = ()=> {
    return fetch('https://api.covid19api.com/countries')
    .then((response) => response.json())
    .then((responseJson) => {
        setData(responseJson)
        setLoading(false)
        setArrayholder(responseJson)
    }

    )
    .catch((error) => {
        console.error(error);
      });
}

  useEffect(() => {
    fetchAPI();
  },[])


  const searchData= (text)=>  {
    const newData = arrayholder.filter(item => {
      const itemData = item.Country.toUpperCase();
      const textData = text.toUpperCase();
      return itemData.indexOf(textData) > -1
    });

      setData(newData)
      setText(text)
    }

   const itemSeparator = () => {
      return (
        <View
          style={{
            height: .5,
            width: "100%",
            backgroundColor: "#000",
          }}
        />
      );
    }

      return (
          <View style={{flex:1}} >
    {loading === false ?  
        <View style={styles.MainContainer}>

        <TextInput 
         style={styles.textInput}
         onChangeText={(text) => searchData(text)}
         value={text}
         underlineColorAndroid='transparent'
         placeholder="Search Here" />

        <FlatList
          data={data}
          keyExtractor={ (item, index) => index.toString() }
          ItemSeparatorComponent={itemSeparator}
          renderItem={( {item}  ) => <Text style={styles.row}
           >{item.Country}</Text>}
          style={{ marginTop: 10 }} />

      </View>
      : <Text>loading</Text>}

      </View>
    );
  }


const styles = StyleSheet.create({

  MainContainer: {
    paddingTop: 50,
    justifyContent: 'center',
    flex: 1,
    margin: 5,

  },

  row: {
    fontSize: 18,
    padding: 12
  },

  textInput: {

    textAlign: 'center',
    height: 42,
    borderWidth: 1,
    borderColor: '#009688',
    borderRadius: 8,
    backgroundColor: "#FFFF"

  }
});

这篇关于React Native Hooks 搜索过滤器 FlatList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆