1

我在使用 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,
  },
})

谢谢

4

2 回答 2

1

React 钩子只能与功能组件一起使用,这里您使用的是类组件

您需要首先了解功能组件和类组件之间的区别

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

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
于 2021-01-23T12:26:13.437 回答
0

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

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
于 2021-01-23T12:43:01.827 回答