reactjs - 我不明白 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;
解决方案
请先阅读文档:https ://react-redux.js.org/api/connect
我会给你redux的基础知识让你能正确理解
connect(mapStateToProps, mapDispatchToProps)(Component)
这里
connect 是一个函数,可以将你
redux
的组件与你的组件连接起来,redux state
并actions/dispatch
在你的组件道具中添加你的和。where
mapStateToProps
是一个功能,state as an argument
你可以all redux state
从那里访问,你可以使用this.props.stateName
哪里
mapDispatchToProps
有一个函数可以帮助你调用你的动作,比如this.props.actionName
推荐阅读
- django - sqs消息删除流程如何在celery-sqs中工作
- ruby-on-rails - 使用用户参数过滤用户帖子
- php - Jetpack 无限滚动在首页中不起作用
- acumatica - GI 屏幕中的列排序
- python - 为什么使用循环打印时顺序没有正确排序?
- python - 将基于列表的熊猫数据框导出到 Excel 的问题
- php - 使用转换后的预处理语句 SQLi 无法登录
- html - 在WordPress自定义css中悬停时背景颜色不会改变
- c++ - 将 GtkTreeView 中的 Cell 设置为以编程方式编辑模式
- javascript - jquery 关于属性(从加载的 html 加载)