0

Estive tentando adicionar Items em uma FlatList no React Native, então usei o seguinte código:

export default function App(){

  var list = [

    {text: 'Hello', key: 1},
    {text: 'Bye', key: 2}

  ]

  return(

    <View style={{flex: 1, backgroundColor: '#fff', justifyContent: 'center', alignItems: 'center'}}>
      <FlatList data={list} showsVerticalScrollIndicator = {false}
      renderItem= { ({ item }) => (

      <Text style={{marginTop: 40}}>{item.text}</Text>

      ) }/>
      <TouchableOpacity style={{marginBottom: 40}} onPress={ () => list.push({text: 'Hi', key: 3}) }>
        <Text>Hello</Text>
      </TouchableOpacity>
    </View>

  )

}

Porém quando eu clico no botão, simplesmente nada acontece, alguém sabe exatamente o porquê?

1 Resposta 1

1

O botão pode até estar adicionando o seu item na lista, porém o react não sabe que precisa renderizar novamente os dados da FlatList.

Para você trabalhar com esse tipo de mudança no estado dos dados da aplicação, você deve utilizar o state do react:

https://reactnative.dev/docs/intro-react#state


Então, você passa a importar a função useState:

import React, { useState } from 'react';

A sua lista, passa a ser criada via a função useState, que vai lhe devolver a lista e também uma função de set para a lista:

const [list, setList] = useState(
                         [
                           {text: 'Hello', key: 1},
                           {text: 'Bye'  , key: 2}
                         ]
                        );

Perceba que já criei a lista com os valores que você tinha.

Com isso, agora você tem a função setList, que quando utilizada, o react vai saber que precisa renderizar novos dados.

Podemos criar uma função que será a responsável por adicionar os itens na lista, utilizando a setList:

let key = list.length;

function addToList() {
  list.push({text: 'Hi', key: ++key});
  setList([...list]);
}

Fiz uma pequena alteração para que a key sempre seja diferente para evitar erros, é apenas um exemplo.

Agora basta chamar a função addToList no onPress do TouchableOpacity:

<TouchableOpacity style={{marginBottom: 40}} onPress={ () => addToList() }>

Seu código completo vai ficar mais ou menos da seguinte forma:

import React, { useState } from 'react';
import { Text, View, FlatList, TouchableOpacity} from 'react-native';

export default function App() {

  const [list, setList] = useState(
                            [
                              {text: 'Hello', key: 1},
                              {text: 'Bye'  , key: 2}
                            ]
                          );
  let key = list.length;

  function addToList() {
    list.push({text: 'Hi', key: ++key});
    setList([...list]);
  }

  return(

    <View style={{flex: 1, backgroundColor: '#fff', justifyContent: 'center', alignItems: 'center'}}>

      <FlatList data={list} showsVerticalScrollIndicator = {false}
          renderItem= { ({ item }) => (

          <Text style={{marginTop: 40}}>{item.text}</Text>

      ) }/>

      <TouchableOpacity style={{marginBottom: 40}} onPress={ () => addToList() }>
          <Text>Hello</Text>
      </TouchableOpacity>

    </View>

  );

}

Veja online: https://snack.expo.io/tvAPFZfB3

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .