Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
570 views
in Technique[技术] by (71.8m points)

react native - How can use useState() with Flatlist data?

I've had a problem when i used useState(). i have to filter by searched words on my data and list.

i need to define my data list with State (i'd list with searched words) but when i use State, i've taken 'Invalid Hook' error.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

React hooks can be used with functional component only, here you are using class component

You need to understand the difference between functional component and class component first.

Here you are using class component so your state should be manageed in the following way

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

and to update list

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

If you want to use hooks, your component needs to be changed something like the following:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...