Tengo un problema al mostrar este código en el navegador, ¿hay alguna forma de solucionarlo? Si se necesita más información, hágamelo saber. Recibo el error en el componenteDidMount. ¿Hay algo que estoy haciendo mal?
El PostService se publica en la parte inferior.
import React, { Component } from 'react'; import PostService from '../services/PostService'; class ListPost extends Component { constructor(props) { super(props); this.state = { posts: [] }; } componentDidMount(){ PostService.getPosts().then((response) => { this.setState({ posts: response.data }); }); } render() { return ( <div> <h2 className="text-center">Posts</h2> <div className="row"> <table className="table table--striped table-boarded"> <thead> <tr> <th>Title</th> <th>Description</th> <th>Content</th> </tr> </thead> <tbody> { this.state.posts.map( post => <tr key={post?.id}> <td>{post?.description}</td> <td>{post?.title}</td> <td>{post?.content}</td> </tr> )} </tbody> </table> </div> </div> ) } } export default ListPost; import axios from "axios"; const POST_API_BASE_URL = "http://localhost:8080/api/posts"; class PostService { getPosts() { axios.get(POST_API_BASE_URL); } } export default new PostService();En primer lugar, cambie su PostService a;
import axios from "axios"; const POST_API_BASE_URL = "http://localhost:8080/api/posts"; export default function getPosts() { return axios.get(POST_API_BASE_URL); } E importar como import getPosts from '../services/PostService'; en su clase ListPost .
A continuación, utilice el código de abajo. No deberías establecer el estado dentro componentDidMount
componentDidMount() { this.getData(); } getData = () => { getPosts() .then(response => { this.setState({ posts: response.data }); }) .catch(error => { // handle errors here }) }