Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

99
Vistas
Cómo volver a renderizar React Component cuando se llama a una función externa

Creé un objeto de clase que almacena la lista de publicaciones. Cuando se actualizó la publicación, se registró la función de suscripción al patrón Pub-Sub.

 class PostLoad extends PubSub { store = []; constructor (){ super(); this.connectSocket = connectSocket(this.projectUid, async (type, post) => { console.log('Socket HOOK', type, post); if (type === 'insert') await this.newPostPush(post); if (type === 'update') { const {deleted} = post; if (deleted) await this.deletePostInStore(post.id); } }); } async postLoad () { // ...API LOAD const value = axios.get(''); this.store = value; } private async newPostPush(post: HashsnapPostItem) { if (post.type === 'video') return; const storeItem = {...post, img: await loadImage(post.url)} as HashsnapPost; this.store.unshift(storeItem); if (this.store.length > this.limit) this.store.splice(this.limit); this.emit('insert', {post: storeItem, store: this.store}); } private deletePostInStore(targetId: number) { this.store.push(...this.store.splice(0).filter(({id}) => id !== targetId)); this.emit('delete', {postId: targetId, store: this.store}); } }

El componente React ejecuta eventos registrados en Pub-Sub. Cuando se actualizó la publicación, se cambió el valor de estado, pero no hubo ningún cambio.

 const PostList = () => { const [postList, setPostList] = useState([]); const postLoad = store.get('postLoad'); // PostLoad Class Object useEffect(() => { setPostList(postLoad.store); }, []); postLoad.on('delete', (payload) => { setPostList(postLoad.store); }) postLoad.on('insert', (payload) => { setPostList(postLoad.store); }) return <div> {postList.map((post, i) => { return <div key={`post-${i}`}></div> })} </div> }

Lo que quiero es que cuando se ejecute el evento Pus-Sub, el valor de estado cambie y se vuelva a generar.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

 async postLoad () { // ...API LOAD- axios is a async func, need await this const value = await axios.get(''); this.store = value; } postLoad.on('delete', (payload) => { setPostList(postLoad.store); }) postLoad.on('insert', (payload) => { setPostList(postLoad.store); }) // thest two register on postLoad will repeat many times, just use hook useEffect, if postLoad always change, useRef, so the right code is below const PostList = () => { const [postList, setPostList] = useState([]); const {current: postLoad} = useRef(store.get('postLoad')); useEffect(() => { setPostList(postLoad.store); postLoad.on('delete', (payload) => { setPostList(postLoad.store); }) postLoad.on('insert', (payload) => { setPostList(postLoad.store); }) return () => { // please unregister delete and insert here } }, [postLoad]); return <div> {postList.map((post, i) => { return <div key={`post-${i}`}></div> })} </div> }

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda