简体   繁体   中英

React Redux mapStateToProps loads data in the second call

mapStatToProps is callings it's self twice and loads data on the second call but then doesn't assign it to components as a prop and returns an empty array.

The Reducer:

 export default function postsReducer(state = initialState.posts, action) {
  switch (action.type) {
    case types.LOAD_POSTS_SUCCESS:
      return action.posts;
    default:
      return state;
  }
 }

Here is my mpStateToProps func:

function mapStateToProps(state, ownProps) {
     const singlePost = state.posts.filter(post => post.code == ownProps.params.id);
      return {
        post: singlePost
     };
   }

Here is my Component's state:

this.state = {
   post: [...props.post]
};

Your code is probably right, but it seems like you forgot to update your state.post value when your component receives new props.

componentWillReceiveProps(nextProps) {
  this.setState({
    post: nextProps.post
  });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM