最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to use map() with data from axios response? - Stack Overflow

programmeradmin4浏览0评论

I'm using axios to get data from the server and storing it in the state. When I do state.map( post => {console.log(post)} ), I do not see anything.

I'm using Express, Mongoose, NextJS and Axios.

I'm using axios to get data from the server and storing it in this.state.posts. When I do console.log(this.state.posts) in componentDidMount, it logs the posts array perfectly. But when I do the same in render(){ return ( /*here*/)} it does not show anything.

This logs all the posts without an error

async componentDidMount() {     
        const { data } = await axios.get('/api/all')
        this.setState({posts: data, isLoading: false})
        console.log(this.state.posts)
    }

But this does not log anything -

render() {
  return({ 
    posts.map( post => {
      <Post title={post.title} />
    })  
  })
}

I'm using axios to get data from the server and storing it in the state. When I do state.map( post => {console.log(post)} ), I do not see anything.

I'm using Express, Mongoose, NextJS and Axios.

I'm using axios to get data from the server and storing it in this.state.posts. When I do console.log(this.state.posts) in componentDidMount, it logs the posts array perfectly. But when I do the same in render(){ return ( /*here*/)} it does not show anything.

This logs all the posts without an error

async componentDidMount() {     
        const { data } = await axios.get('/api/all')
        this.setState({posts: data, isLoading: false})
        console.log(this.state.posts)
    }

But this does not log anything -

render() {
  return({ 
    posts.map( post => {
      <Post title={post.title} />
    })  
  })
}
Share Improve this question edited Jun 11, 2019 at 11:36 Vencovsky 31.6k22 gold badges130 silver badges195 bronze badges asked Jun 11, 2019 at 11:33 Ajay YadavAjay Yadav 1711 gold badge2 silver badges11 bronze badges 1
  • Try to wrap your jsx code with <React.Fragment> – bkm412 Commented Jun 11, 2019 at 11:38
Add a comment  | 

7 Answers 7

Reset to default 5
{ 
   posts.map( post => {
    return <Post title={post.title} />
}) 
}

Maybe it works.

You can provide callback to setState method which will run after the state is updated. You can use

this.setState({posts: data, isLoading: false}, () => console.log(this.state.posts))

to log updated state.

And in render method you should use

render() {
  return(
    this.state.posts.map( (post,i) => (
      <Post title={post.title} key={i} />
    ))  
  )
}

or

 render() {
  const { posts} = this.state;
   return(
      <React.Fragment>
       posts.map( (post,i) => (
        <Post title={post.title} key={i} />
       ))  
     </React.Fragment>
   )
 }

Can you try this:

async componentDidMount() {     
        const { data } = await axios.get('/api/all')
        this.setState({posts: data, isLoading: false}, () => {
        console.log(this.state.posts)
        return;
    })    
  }

You need to return direclty posts.map with out opening {}

render() {
  const { posts = [] } = this.state
  return(
    posts.map( post => 
      <Post title={post.title} />
    )  
  )
}

const { posts = [] } will make sure that posts is an array and don't give you any errors like cannot read .map of undefined

Or you can open {} inside a React.Fragment

render() {
  const { posts = [] } = this.state
  return(
    <>
      { 
        posts.map( post => 
          <Post title={post.title} />
        )
      }
    </>    
  )
}

Modify your render method like this:

render() {
  let Posts = {...this.state.posts};
  return({
    Posts.map( post => <Post title={post.title} />);  
  })
}

Your code is not correctly referencing the posts in state. Also,this way any operation on posts will not affect the state object directly. Hope this helps!

async componentDidMount(){

const res = await axios.get('/api/all')
  this.setState({
  post: res.data
  })
}
export default class Blog extends Component {
state = {post:[]}
componentDidMount() {
            // Make a request for a user with a given ID
axios.get('https://jsonplaceholder.typicode.com/posts')
.then((response) => {
    this.setState({post:response.data})
  // handle success
})
.catch(function (error) {
  // handle error
  console.log(error);
})
.then(function () {
  // always executed
});
}render(){
const posts = this.state.post;
 const allposts = posts.map(post =>{
return( 
       <div>{post.title}</div>
 )
});
return(
<div>{allposts}</div>
);
}}
发布评论

评论列表(0)

  1. 暂无评论