博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
什么是mapDispatchToProps?
阅读量:3580 次
发布时间:2019-05-20

本文共 7704 字,大约阅读时间需要 25 分钟。

本文翻译自:

I was reading the documentation for the Redux library and it has this example: 我正在阅读Redux库的文档,其中包含以下示例:

In addition to reading the state, container components can dispatch actions. 除了读取状态之外,容器组件还可以调度动作。 In a similar fashion, you can define a function called mapDispatchToProps() that receives the dispatch() method and returns callback props that you want to inject into the presentational component. 以类似的方式,您可以定义一个名为mapDispatchToProps()的函数,该函数接收dispatch()方法并返回要注入到演示组件中的回调道具。

This actually makes no sense. 这实际上是没有意义的。 Why do you need mapDispatchToProps when you already have mapStateToProps ? 为什么你需要mapDispatchToProps当你已经有mapStateToProps

They also provide this handy code sample: 他们还提供了以下方便的代码示例:

const mapDispatchToProps = (dispatch) => {  return {    onTodoClick: (id) => {      dispatch(toggleTodo(id))    }  }}

Can someone please explain in layman's terms what this function is and why it is useful? 有人可以用外行的术语解释一下此功能是什么以及为什么有用吗?


#1楼

参考:


#2楼

It's basically a shorthand. 基本上是简写。 So instead of having to write: 因此,不必写:

this.props.dispatch(toggleTodo(id));

You would use mapDispatchToProps as shown in your example code, and then elsewhere write: 您将使用示例代码中所示的mapDispatchToProps,然后在其他地方编写:

this.props.onTodoClick(id);

or more likely in this case, you'd have that as the event handler: 或更可能是这种情况,您可以将其用作事件处理程序:


There's a helpful video by Dan Abramov on this here: 丹·阿布拉莫夫(Dan Abramov)在此提供了一个有用的视频: :


#3楼

mapStateToProps receives the state and props and allows you to extract props from the state to pass to the component. mapStateToProps接收stateprops并允许您从状态中提取道具以传递给组件。

mapDispatchToProps receives dispatch and props and is meant for you to bind action creators to dispatch so when you execute the resulting function the action gets dispatched. mapDispatchToProps接收dispatchprops ,它用于绑定操作创建者以进行调度,因此当您执行结果函数时,将调度该操作。

I find this only saves you from having to do dispatch(actionCreator()) within your component thus making it a bit easier to read. 我发现这仅使您不必在组件内执行dispatch(actionCreator()) ,从而使其更易于阅读。


#4楼

mapStateToProps , mapDispatchToProps and connect from react-redux library provides a convenient way to access your state and dispatch function of your store. 通过react-redux库中的mapStateToPropsmapDispatchToPropsconnect提供了一种方便的方法来访问商店的statedispatch功能。 So basically connect is a higher order component, you can also think as a wrapper if this make sense for you. 因此,基本上connect是一个更高阶的组件,如果您认为合适的话,也可以将其视为包装器。 So every time your state is changed mapStateToProps will be called with your new state and subsequently as you props update component will run render function to render your component in browser. 所以每次你的时间state改变mapStateToProps将与新的被称为state ,并随后根据你props更新组件将运行呈现功能呈现在您的浏览器组件。 mapDispatchToProps also stores key-values on the props of your component, usually they take a form of a function. mapDispatchToProps还将键值存储在组件的props上,通常它们采用函数形式。 In such way you can trigger state change from your component onClick , onChange events. 这样,您可以从组件的onClickonChange事件触发state更改。

From docs: 从文档:

const TodoListComponent = ({ todos, onTodoClick }) => (  
    {todos.map(todo =>
    onTodoClick(todo.id)} /> )}
)const mapStateToProps = (state) => { return { todos: getVisibleTodos(state.todos, state.visibilityFilter) }}const mapDispatchToProps = (dispatch) => { return { onTodoClick: (id) => { dispatch(toggleTodo(id)) } }}function toggleTodo(index) { return { type: TOGGLE_TODO, index }}const TodoList = connect( mapStateToProps, mapDispatchToProps)(TodoList)

Also make sure that you are familiar with and 还要确保您熟悉和


#5楼

I feel like none of the answers have crystallized why mapDispatchToProps is useful. 我觉得没有一个答案能mapDispatchToProps说明为什么mapDispatchToProps有用。

This can really only be answered in the context of the container-component pattern, which I found best understood by first reading: then . 实际上,这只能在container-component模式的上下文中得到回答,我首先阅读以下内容可以最好地理解这一点: 然后 。

In a nutshell, your components are supposed to be concerned only with displaying stuff. 简而言之,您的components应该只与显示内容有关。 The only place they are supposed to get information from is their props . 他们应该从中获取信息唯一地方是他们的道具

Separated from "displaying stuff" (components) is: 与“显示内容”(组件)分开的是:

  • how you get the stuff to display, 您如何展示这些东西,
  • and how you handle events. 以及您如何处理事件。

That is what containers are for. 那就是containers的用途。

Therefore, a "well designed" component in the pattern look like this: 因此,模式中的“精心设计” component如下所示:

class FancyAlerter extends Component {    sendAlert = () => {        this.props.sendTheAlert()    }    render() {        

Today's Fancy Alert is {this.props.fancyInfo}

}}

See how this component gets the info it displays from props (which came from the redux store via mapStateToProps ) and it also gets its action function from its props: sendTheAlert() . 查看此组件如何从props(通过mapStateToProps从redux存储库中mapStateToProps )获取它显示的信息,以及如何从props中获取其action函数: sendTheAlert()

That's where mapDispatchToProps comes in: in the corresponding container 那就是mapDispatchToProps进入的地方:在相应的container

// FancyButtonContainer.jsfunction mapDispatchToProps(dispatch) {    return({        sendTheAlert: () => {dispatch(ALERT_ACTION)}    })}function mapStateToProps(state) {    return({fancyInfo: "Fancy this:" + state.currentFunnyString})}export const FancyButtonContainer = connect(    mapStateToProps, mapDispatchToProps)(    FancyAlerter)

I wonder if you can see, now that it's the container that knows about redux and dispatch and store and state and ... stuff. 我不知道您是否可以看到,现在正是container 知道了redux以及dispatch和store以及state和...之类的东西。

The component in the pattern, FancyAlerter , which does the rendering doesn't need to know about any of that stuff: it gets its method to call at onClick of the button, via its props. 模式中的component FancyAlerter进行渲染不需要了解任何这些东西:它通过其道具通过按钮的onClick调用其方法。

And ... mapDispatchToProps was the useful means that redux provides to let the container easily pass that function into the wrapped component on its props. 并且... mapDispatchToProps是redux提供的有用手段,它可以使容器轻松地将该函数传递给其props上的包装组件。

All this looks very like the todo example in docs, and another answer here, but I have tried to cast it in the light of the pattern to emphasize why . 所有这些看起来都非常像docs中的todo示例,还有另一个答案,但是我试图根据模式来强调它为什么

(Note: you can't use mapStateToProps for the same purpose as mapDispatchToProps for the basic reason that you don't have access to dispatch inside mapStateToProp . So you couldn't use mapStateToProps to give the wrapped component a method that uses dispatch . (注:不能使用mapStateToProps为同一目的, mapDispatchToProps不要为您无法访问的基本原因dispatch内部mapStateToProp所以你不能使用。 mapStateToProps给包裹组件使用的方法dispatch

I don't know why they chose to break it into two mapping functions - it might have been tidier to have mapToProps(state, dispatch, props) IE one function to do both! 我不知道他们为什么选择将其分为两个映射函数-可能只有mapToProps(state, dispatch, props) IE一个函数可以同时完成这两个任务!


Note that I deliberately explicitly named the container FancyButtonContainer , to highlight that it is a "thing" - the identity (and hence existence!) of the container as "a thing" is sometimes lost in the shorthand 请注意,我故意将容器明确命名为FancyButtonContainer ,以强调它是“事物”-容器的“物”的身份(因此存在!)有时会在速记中丢失

export default connect(...) ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ export default connect(...)

syntax that is shown in most examples 大多数示例中显示的语法


#6楼

mapStateToProps() is a utility which helps your component get updated state(which is updated by some other components), mapStateToProps()是一个实用程序,可帮助您的组件获取更新的状态(由其他某些组件更新),

mapDispatchToProps() is a utility which will help your component to fire an action event (dispatching action which may cause change of application state) mapDispatchToProps()是一个实用程序,可以帮助您的组件触发操作事件(调度操作可能会导致应用程序状态更改)

转载地址:http://rllgj.baihongyu.com/

你可能感兴趣的文章
一篇认识 Zookeeper
查看>>
一篇认识kafka
查看>>
Kafka 实战
查看>>
一篇认识 Elasticsearch
查看>>
爬虫篇——腾讯新闻的详细采集过程(列表新闻和新闻内容)
查看>>
NIO 服务器端不阻塞的一个Bug解决
查看>>
DM数据库的安装部署和卸载
查看>>
DM8数据库体系结构
查看>>
DM模式对象的基本操作
查看>>
springMVC之controller笔记
查看>>
springmvc类型转换
查看>>
ai 的研究生院校
查看>>
oracle中的函数trunk()和.truncate()和add_months()
查看>>
运维要求
查看>>
腾讯云Ubuntu18.04部署javaweb项目要做的配置
查看>>
Windows10+Ubuntu(Linux)双系统安装
查看>>
Git+Hexo 搭建博客教程
查看>>
【数据结构】C语言线性表-顺序表
查看>>
Vim强化配置(效果堪比IDE)
查看>>
【VS Code】Code Runner插件修改默认为python3
查看>>