En mi padre (Feed) muestro una lista de publicaciones:
function Feed() { const [posts, setPosts] = useState(null); useEffect(() => { const fetchPosts = async () => { try { const result = await axios({ ... }); setPosts(result.data); ... } catch (e) { ... } }; fetchPosts(); }, []); return ( ... {posts && <div> <PostCompose /> // post creation {posts.map((item, index) => // map existing posts <Post key={item._id} {...item} />)} </div> } ... ) }El niño (PostCompose) puede crear una publicación:
function PostCompose() { const [text, setText] = useState(''); const createPost = async () => { try { const result = await axios({ ... }) ... } catch (e) { ... } } const handleTextChange = (e) => { setText(e.target.value); } return ( ... <textarea onChange={handleTextChange} /> <button onClick={createPost}>Post</button> ... ) }El componente PostCompose realiza las solicitudes al backend para crear las nuevas publicaciones, pero ¿cómo activo el Feed para que se actualice y extraiga la nueva lista de publicaciones?
Siento que mi enfoque podría necesitar algo de trabajo, cualquier ayuda sería genial ya que soy muy nuevo en React. Gracias.
Una forma sería quitar la función fetchPosts del efecto de devolución de llamada, usando el ganchouseCallback para memorizarlo. Ahora puede invocar fetchPosts cuando se monta el componente Feed y proporcionarlo a su componente PostCompose , como lo he hecho aquí con la propiedad afterPostCreated :
function Feed() { const [posts, setPosts] = useState(null); const fetchPosts = useCallback(async () => { try { const result = await axios({ // ... }); setPosts(result.data); // ... } catch (e) { // ... } }, []); useEffect(() => { fetchPosts(); }, [fetchPosts]); return ( posts && ( <div> <PostCompose afterPostCreated={fetchPosts} /> // post creation {posts.map( ( item, index // map existing posts ) => ( <Post key={item._id} {...item} /> ) )} </div> ) ); } Luego simplemente invoque esa devolución de llamada en su componente PostCompose , después de que la publicación se haya creado con éxito:
function PostCompose({ afterPostCreated }) { const [text, setText] = useState(''); const createPost = async () => { try { const result = await axios({ // ... }); // ... if (afterPostCreated) { afterPostCreated(); } } catch (e) { // ... } }; const handleTextChange = (e) => { setText(e.target.value); }; return ( <> <textarea onChange={handleTextChange} /> <button onClick={createPost}>Post</button> </> ); }