const addComment = (c:IComment) => {
if(post){
var p = post // creating a copy of my post state
p.comments = [c,...p.comments] // creating new comments array with the new comment and all old ones
setPost(p) // setting post state to be newly updated post
console.log(post) // console log confirms state has in fact been changed and the new comment is there
// component has not re rendered....
}`
}
lo siento, la opción de formato de código aquí no parece funcionar. Pero este es básicamente el problema, cambiar mi estado funciona bien, pero el componente simplemente se niega a volver a renderizar cuando cambia su estado.
Solución del problema
El problema es la forma en que clonaste la publicación. Se requiere una copia profunda de la publicación para resolver este problema.
1- Usando el operador de propagación
const addComment = (c:IComment) => {
if(post){
const p = {...post}
p.comments = [c,...p.comments]
setPost(p)
}
}
No hay comentarios:
Publicar un comentario