Saltar al contenido

¿Cómo actualizar un solo elemento en FlatList en React Native?

Hacemos una verificación exhaustiva cada enunciados de nuestra web con el objetivo de mostrarte en todo momento información con la mayor veracidad y actual.

Solución:

Puedes configurar extraData en FlatList:

 

Cuando state.posts o state.postscambio de artículo, FlatList volverá a renderizar.

De FlatList # extradata:

Una propiedad de marcador para decirle a la lista que se vuelva a renderizar (ya que implementa PureComponent). Si alguna de sus funciones renderItem, Encabezado, Pie de página, etc.depende de algo fuera del soporte de datos, péguelo aquí y trátelo de manera inmutable.

No me malinterpretes, la respuesta de @ShubhnikSingh ayudó, pero me retracté porque encontré una mejor solución a esta pregunta, hace mucho tiempo, y finalmente me acordé de publicarla aquí.

Supongamos que mi artículo de publicación contiene estas propiedades:


    postId: "-L84e-aHwBedm1FHhcqv",
    date: 1525566855,
    message: "My Post",
    uid: "52YgRFw4jWhYL5ulK11slBv7e583",
    liked: false,
    likeCount: 0,
    commentCount: 0

Dónde liked representa si al usuario que ve esta publicación le ha gustado esta publicación, lo que determinará el color del botón “Me gusta” (de forma predeterminada, es gris, pero rojo si liked == true)


Estos son los pasos para volver a crear mi solución: hacer que “Publicar” sea Component y renderizarlo en un FlatList. Puedes usar React’s PureComponent si no tiene ningún accesorio que le pase a su Post como un array u objeto que puede ser engañosamente no superficial igual. Si no sabe lo que eso significa, utilice un Component y anular shouldComponentUpdate como hacemos a continuación.

class Post extends Component                                                       
  // This determines whether a rendered post should get updated                     
  // Look at the states here, what could be changing as time goes by?               
  // Only 2 properties: "liked" and "likeCount", if the person seeing               
  // this post ever presses the "like" button                                       
  // This assumes that, unlike Twitter, updates do not come from other              
  // instances of the application in real time.                                     
  shouldComponentUpdate(nextProps, nextState)                                                                                  

  render()                                                                         
    return (                                                                        
                                                                              
        /* ...render other properties */                                          
         this.props.onPressLike(this.props.postId)                 
        >                                                                           
                     
                                                                 
                                                                             
    )                                                                               
                                                                                   
                                                                                   

Luego, crea un PostList componente que se encargará de manejar la lógica para cargar publicaciones y manejar interacciones similares:

class PostList extends Component                                                         

/**                                                                                       
 * As you can see, we are not storing "posts" as an array. Instead,                       
 * we make it a JSON object. This allows us to access a post more concisely               
 * than if we stores posts as an array. For example:                                      
 *                                                                                        
 * this.state.posts as an array                                                           
 * findPost(postId)                                                                      
 *   return this.state.posts.find(post => post.id === postId)                             
 *                                                                                       
 * findPost(postId)                                                                      
 *   return this.state.posts[postId]                                                      
 *                                                                                       
 * a specific post by its "postId", you won't have to iterate                             
 * through the whole array, you can just call "posts[postId]"                             
 * to access it immediately:                                                              
 * "posts":                                                                              
 *     "":  "message": "", "uid": "", ... ,                                  
 *     "":  "message": "", "uid": "", ... ,                                  
 *     "":  "message": "", "uid": "", ...                                    
 *                                                                                       
 * FlatList wants an array for its data property rather than an object,                   
 * so we need to pass data=Object.values(this.state.posts) rather than                  
 * just data=this.state.posts as one might expect.                                      
*/                                                                                        

  state =                                                                                  
    posts:                                                                                
    // Other states                                                                         
                                                                                           

  renderItem = ( item ) => 
    const  date, message, uid, postId, other, props, here  = item
    return (
      
    )
  

  handleLikePost = postId => 
    let post = this.state.posts[postId]
    const  liked, likeCount  = post

    const newPost = 
      ...post,
      liked: !liked,
      likeCount: liked ? likeCount - 1 : likeCount + 1
    

    this.setState(
      posts: 
        ...this.state.posts,
        [postId]: newPost
      
    )
  

  render() 
    return (
      
         item.postId
        />
      
    )
  

En resumen:

1) Escriba un componente personalizado (Post) para representar cada elemento en “FlatList”

2) Anule “shouldComponentUpdate” del componente personalizado (Post) función para decirle al componente cuándo actualizar

Manejar el “estado de Me gusta” en un componente principal (PostList) y transmitir datos a cada niño

Si está probando en Android, intente desactivar el modo de desarrollador. ¿O está presionando alguna API y actualizando la publicación en el servidor y actualizando el botón Me gusta en la interfaz de usuario correspondiente a la respuesta del servidor? Si ese es el caso, dímelo, yo también me encontré con esto y lo resolví. También he comentado la penúltima línea de su código que no es necesaria.

// 1. FlatList
 

// 2. renderPost
renderPost( item, index ) 
    return (
        
            ... // display other properties of the post
            // Then display the "like" button
             this.onLikePost( item, index )
            />
            ...
        
    );


// 3. onLikePost
likePost( item, index ) 
    let  posts  = this.state;
    let targetPost = posts[index];

    // Flip the 'liked' property of the targetPost
    targetPost.liked = !targetPost.liked;

    // Then update targetPost in 'posts'
    // You probably don't need the following line.
    // posts[index] = targetPost;

    // Then reset the 'state.posts' property
    this.setState( posts );

¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)



Utiliza Nuestro Buscador

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *