Advertisement
Uno-Dan

Class component

Mar 27th, 2021
781
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import React, { Component } from 'react'
  2. import PropTypes from 'prop-types'
  3. import { connect } from 'react-redux'
  4. import { fetchPosts } from '../actions/postActions'
  5.  
  6. class Posts extends Component {
  7.   componentWillMount() {
  8.     this.props.fetchPosts()
  9.   }
  10.  
  11.   componentWillReceiveProps( nextProps ) {
  12.       if ( nextProps.newPost ) {
  13.         this.props.posts.unshift( nextProps.newPost )
  14.       }
  15.     }
  16.  
  17.   render () {
  18.     const postItems = this.props.posts.map( post => (
  19.       <div key={ post.id }>
  20.         <h3>{ post.title }</h3>
  21.         <p>{ post.body }</p>
  22.       </div>
  23.     ) )
  24.  
  25.     return(
  26.       <div>
  27.         <h1>Posts</h1>
  28.         { postItems }
  29.       </div>
  30.     )
  31.   }
  32. }
  33.  
  34. Posts.propTypes = {
  35.   fetchPosts: PropTypes.func.isRequired,
  36.   posts: PropTypes.array.isRequired,
  37.   newPost: PropTypes.object
  38. }
  39.  
  40. const mapStateToProps = state => ( {
  41.   posts: state.posts.items,
  42.   newPost: state.posts.item
  43. } )
  44.  
  45. export default connect(mapStateToProps, { fetchPosts } )( Posts );
  46.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement