首页 > 解决方案 > 我不明白 redux 函数中的连接是如何工作的

问题描述

我正在尝试使用博客教程中的示例代码来了解 redux 的工作原理,但我无法弄清楚该connect函数在此示例中是如何工作的。请详细说明。

函数connect,看不懂(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;

标签: reactjsredux

解决方案


请先阅读文档:https ://react-redux.js.org/api/connect

我会给你redux的基础知识让你能正确理解

connect(mapStateToProps, mapDispatchToProps)(Component)

这里

  1. connect 是一个函数,可以将你redux的组件与你的组件连接起来,redux stateactions/dispatch在你的组件道具中添加你的和。

  2. wheremapStateToProps是一个功能,state as an argument你可以all redux state从那里访问,你可以使用this.props.stateName

  3. 哪里mapDispatchToProps有一个函数可以帮助你调用你的动作,比如this.props.actionName


推荐阅读