reactjs – 如果没有mapDispatchToProps,connect如何工作

前端之家收集整理的这篇文章主要介绍了reactjs – 如果没有mapDispatchToProps,connect如何工作前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在阅读redux的示例文档,我发现了这个容器组件的例子.有人可以解释为什么在这种情况下不需要mapDispatchToProps.同样,函数如何获得调度功能
import React from 'react'
import { connect } from 'react-redux'
import { addTodo } from '../actions'

let AddTodo = ({ dispatch }) => {
let input

return (
    <div>
      <form onSubmit={e => {
        e.preventDefault()
        if (!input.value.trim()) {
          return
        }
        dispatch(addTodo(input.value))
        input.value = ''
      }}>
        <input ref={node => {
          input = node
        }} />
        <button type="submit">
          Add Todo
        </button>
      </form>
    </div>
  )
}
AddTodo = connect()(AddTodo)

export default AddTodo
connect()(AddTodo)将调度作为prop传递给AddTodo组件,即使没有状态或预定义的操作,它仍然有用.这就是你的代码中不需要mapDispatchToProps的原因

现在,在您的组件中,让AddTodo =({dispatch})=> {您正在将您的道具解构为仅访问调度.

如果您使用mapDispatchToProps,您将使addTodo操作可用作组件的prop,然后像this.props.addTodo一样调用它.所以上面的方法是另一种选择.这取决于你选择你觉得舒服的东西

connect只是通过React上下文传递存储/调度,因此您不必通过许多组件传递存储.您不必使用连接.任何模块/ HOC模式都可以工作,连接恰好是一个方便的东西.

在组件中使用dispatch或使用mapDispatchToProps是同一件事.

但是,使用mapDispatchToProps可以更灵活地构建代码并将所有动作创建者放在一个位置.

根据docs

[mapDispatchToProps(dispatch,[ownProps]): dispatchProps] (Object or Function):

If an object is passed,each function inside it is assumed to be a Redux action creator. An object with the same function names,but with
every action creator wrapped into a dispatch call so they may be
invoked directly,will be merged into the component’s props.

If a function is passed, it will be given dispatch as the first parameter. It’s up to you to return an object that somehow uses
dispatch to bind action creators in your own way. (Tip: you may use
the bindActionCreators() helper from Redux.)

If your mapDispatchToProps function is declared as taking two
parameters,it will be called with dispatch as the first parameter and
the props passed to the connected component as the second parameter,
and will be re-invoked whenever the connected component receives new
props. (The second parameter is normally referred to as ownProps by
convention.)

If you do not supply your own mapDispatchToProps function or object
full of action creators,the default mapDispatchToProps implementation just injects dispatch into your component’s props.

猜你在找的React相关文章