gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 14:00:20 40 4
gpt4 key购买 nike

我很难理解这个神奇的论点 dispatchcontainers/AddTodo.js 的示例中,它突然作为演示组件的第一个参数突然出现。 .

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

AddTodo = connect()(AddTodo)

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

在这种情况下,演示组件似乎被注入(inject)了 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 参数如何出现在演示组件中?

最佳答案

当您在 AddTodo = connect()(AddTodo) 中使用 connect() 时,您将使用 注入(inject) AddTodo 组件调度而不监听存储。 dispatch 现在可以通过 props 在您的组件中使用。如果您使用参数解构,则可以调用 this.props.dispatch() 或直接调用 dispatch() ,即 let 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.

关于reactjs - 组件如何神奇地接收 `dispatch` 作为其第一个参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39792324/

40 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com