如何将 useState() 与 Flatlist 数据一起使用?

How can use useState() with Flatlist data?

我在使用 useState() 时遇到了问题。我必须按我的数据和列表中的搜索词进行过滤。

我需要用 State 定义我的数据列表(我会用搜索词列出)但是当我使用 State 时,我遇到了 'Invalid Hook' 错误。

let [list, setList] = useState(data);

//called
data={list}

我找不到我在哪里使用它,我无法修复 3 天,我无法进行下一步:(我希望我能在专家的帮助下修复...

import React, {Component, useState} from 'react'
import {
  Text,
  StyleSheet,
  View,
  FlatList,
  SafeAreaView,
  ScrollView,
  Image,
  TextInput,
} from 'react-native'
import data from '../../data'

export default class Flatlistexample extends Component {
  render () {
    //defined below
    let [list, setList] = useState(data);

    seachFilter=(text)=>{
      
      const newData = data.filter(item=>{
        const listitem= `${item.name.toLowerCase()} ${item.company.toLowerCase()}`;

        return listitem.indexOf(text.toLowerCase())
      })
    };
    
    return (
      <SafeAreaView
        style={{
          flex: 1,
        }}>
        <FlatList

        //called
          data={list}

          renderItem={({item, index})=>{
      
            return (
              <ScrollView>
                <SafeAreaView
                  style={[
                    styles.container,
                    {backgroundColor: index % 2 === 0 ? '#fafafa' : '#bbb'},
                  ]}>
                  <Image style={styles.profile} source={{uri: item.picture}} />
                  <View style={styles.rightside}>
                    <Text style={styles.name}>{item.name}</Text>
                    <Text style={styles.company}>{item.company}</Text>
                  </View>
                </SafeAreaView>
              </ScrollView>
            )
          
        }}
          
          
          keyExtractor={item => item._id}
          
          ListHeaderComponent={() => {
            const [search, setSearch] = useState('');
            
            
            return (
              
              <View style={styles.seachContainer}>
                <TextInput
                  style={styles.textInput}
                  placeholder={'Search...'}
                  value={search}
                  onChangeText={text=>{
                    setSearch(text)
                  }}
                  ></TextInput>
              </View>
            )
          }}
          
        />
      </SafeAreaView>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flexDirection: 'row',
    alignItems: 'center',
    borderBottomWidth: 1,
    borderColor: 'gray',
  },
  profile: {
    width: 50,
    height: 50,
    borderRadius: 25,
    marginLeft: 10,
  },
  rightside: {
    marginLeft: 20,
    justifyContent: 'space-between',
    marginVertical: 5,
  },
  name: {
    fontSize: 22,
    marginBottom: 10,
  },
  searchContainer: {
    padding: 10,
    borderWidth: 2,
    borderColor: 'gray',
  },
  textInput: {
    fontSize: 16,
    backgroundColor: '#f9f9f9',
    padding: 10,
  },
})

谢谢

React hooks 只能与功能组件一起使用,这里你使用的是 class 组件

你需要先了解difference between functional component and class component

您在这里使用 class 组件,因此您的状态应按以下方式管理

export default class Flatlistexample extends Component {
    constructor(props)
    {
        this.state={list:[]}
    }
}

并更新 list

this.setState({list: <array of data>})

如果你想使用钩子,你的组件需要像下面这样改变:

const Flatlistexample = () => {
  //defined below
  let [list, setList] = useState(data);

  seachFilter = (text) => {
    const newData = data.filter(item => {
      const listitem = `${item.name.toLowerCase()} ${item.company.toLowerCase()}`;

      return listitem.indexOf(text.toLowerCase())
    })
  };

  return (
    <SafeAreaView
      style={{
        flex: 1,
      }}>
      <FlatList data={list} renderItem={Your flatlist Item}/>
    </SafeAreaView>
  )
}

export default Flatlistexample

给你,我添加了很多评论。我希望你觉得这很有启发性。如果您有任何问题,请告诉我!

import React, { useMemo, useState } from 'react'
import {
  Text,
  StyleSheet,
  View,
  FlatList,
  SafeAreaView,
  ScrollView,
  Image,
  TextInput,
} from 'react-native'
import data from '../../data'

// changed this to a functional component so you can use hooks. You can't use hooks in class components.
const Flatlistexample = () => {
  // you don't actually need to `useState` for your list, since you're always just filtering `data`
  // you would need to use `useState` if you were receiving data from an API request, but here it's static

  const [search, setSearch] = useState('') // this should live in the main component so you can filter the list

  const parsedSearch = search.toLowerCase() // do this once outside the filter, otherwise you're converting it for each item in the data array

  const filteredList = useMemo(
    () =>
      data.filter(item => {
        const itemText = `${item.name.toLowerCase()} ${item.company.toLowerCase()}`
        return itemText.indexOf(parsedSearch) > -1 // returns `true` if search is found in string
      }),
    [parsedSearch], // this will only run if parsedSearch changes
  )

  return (
    <SafeAreaView style={{ flex: 1 }}>
      <FlatList
        //called
        data={filteredList} // use the filtered list here
        renderItem={({ item, index }) => {
          return (
            <ScrollView>
              <SafeAreaView
                style={[
                  styles.container,
                  { backgroundColor: index % 2 === 0 ? '#fafafa' : '#bbb' },
                ]}
              >
                <Image style={styles.profile} source={{ uri: item.picture }} />
                <View style={styles.rightside}>
                  <Text style={styles.name}>{item.name}</Text>
                  <Text style={styles.company}>{item.company}</Text>
                </View>
              </SafeAreaView>
            </ScrollView>
          )
        }}
        keyExtractor={item => item._id}
        ListHeaderComponent={() => {
          return (
            <View style={styles.seachContainer}>
              <TextInput
                style={styles.textInput}
                placeholder={'Search...'}
                value={search}
                onChangeText={text => {
                  setSearch(text)
                }}
              />
            </View>
          )
        }}
      />
    </SafeAreaView>
  )
}

export default Flatlistexample