-1

I'm trying to understand how redux works using the example code from the blog tutorial, but I can't figure out how the connect function works in this example. Please explain in detail.

Function connect, I don't understand (items) => items, PostListActions

export default connect((items) => items, PostListActions)(PostListContainer);
import React from 'react';
import {connect} from 'react-redux';
import {PostList} from '../../../components/PostList';
import PostListActions from "./../actions";

export class PostListContainer extends React.Component {

    componentWillMount() {
        const {fetchItems} = this.props;
        fetchItems();
    }

    render() {
        const {fetchRemoveItem} = this.props;
        return <PostList posts={this.props.posts.items} onRemove = {fetchRemoveItem}/>;
    }

}


export default connect((items) => items, PostListActions)(PostListContainer);
import {postApi} from './../../utils/api';

const PostListActions = {
    setItems: (items) => ({
        type: 'POSTS:SET_ITEMS',
        payload: items
    }),

    removeItems: (id) => ({
        type: 'POSTS:REMOVE_ITEM',
        payload: id
    }),

    fetchItems: () => dispatch => {
        postApi.getNotes().then(({data}) => {
            dispatch(PostListActions.setItems(data));
        });
    },

    fetchRemoveItem: (id) => dispatch => {
        dispatch(PostListActions.removeItems(id));
        postApi.deleteNote(id);
    }

};

export default PostListActions;
Drew Reese
  • 165,259
  • 14
  • 153
  • 181
kera0106
  • 15
  • 5

1 Answers1

0

Please read the docs first: https://react-redux.js.org/api/connect

I will give you the basic knowledge of redux so you can understand it properly

connect(mapStateToProps, mapDispatchToProps)(Component)

Here

  1. connect is a function that connects your redux with your component and added your redux state and actions/dispatch in your component props.

  2. where mapStateToProps is a function that gives you the state as an argument and you can access all redux state from there and you can access it using this.props.stateName

  3. where mapDispatchToProps is a function that helps you to call your actions like this.props.actionName

Nisharg Shah
  • 16,638
  • 10
  • 62
  • 73