加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

reactjs – 组件如何神奇地接收`dispatch`作为其第一个参数?

发布时间:2020-12-15 09:32:04 所属栏目:百科 来源:网络整理
导读:我很难理解魔术论证 dispatch ,它突然出现在 containers/AddTodo.js 的例子中作为演示组件的第一个参数. let AddTodo = ({ dispatch }) = { /* Omitted */}AddTodo = connect()(AddTodo) 到目前为止,我的理解是第一个AddTodo被认为是Presentation组件,后者是
我很难理解魔术论证 dispatch,它突然出现在 containers/AddTodo.js的例子中作为演示组件的第一个参数.

let AddTodo = ({ dispatch }) => {
    /* Omitted */
}

AddTodo = connect()(AddTodo)

到目前为止,我的理解是第一个AddTodo被认为是Presentation组件,后者是Container组件

在这种情况下,表示组件似乎注入了dispatch作为第一个参数.不幸的是,我回头后感到困惑,并意识到the rest of the presentation component的情况并非如此.

const Todo = ({ onClick,completed,text }) => (
    /* Omitted */
)

Todo.propTypes = {
  onClick: PropTypes.func.isRequired,completed: PropTypes.bool.isRequired,text: PropTypes.string.isRequired
}

dispatch参数如何出现在表示组件中?

解决方法

当您使用connect()时:AddTodo = connect()(AddTodo)您正在使用调度注入AddTodo组件而不监听存储.现在可以通过道具在您的组件中使用dispatch.如果你使用参数解构,它可以被称为this.props.dispatch()或直接作为dispatch(),即让AddTodo =({dispatch})…

以下是官方redux文档中的详细说明:https://github.com/reactjs/react-redux/blob/master/docs/api.md#connectmapstatetoprops-mapdispatchtoprops-mergeprops-options

connect([mapStateToProps],[mapDispatchToProps],[mergeProps],[options])

[mapDispatchToProps(dispatch,[ownProps]): dispatchProps] (Object or Function): If an object is passed,each function inside it will be 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. 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 you omit it,the default implementation just injects dispatch into your component’s props. If ownProps is specified as a second argument,its value will be the props passed to your component,and mapDispatchToProps will be re-invoked whenever the component receives new props.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读