mapDispatchToProps: any point?

前端 未结 2 975
终归单人心
终归单人心 2021-02-07 07:12

I was wondering if there was still a point using mapDispatchToProps today. I\'m working on the redux documentation tutorials (to build a todo list) where Visi

相关标签:
2条回答
  • 2021-02-07 07:33

    To clarify the other Mark's comment:

    The second argument to connect() can take two main forms. If you pass a function as the argument, connect() assumes you want to handle dispatch preparation yourself, calls your function with dispatch as an argument, and merges the result into the props for your component.

    If you pass in an object as the second argument to connect(), it assumes you've given it a map of prop names to action creators, and so it automatically runs all of them through the bindActionCreators utility and uses the result as props.

    However, passing a single action creator as the second argument, as your example appears to do, would not do what you want, as connect() would interpret that as a preparation function and not an action creator that needs to be bound.

    So yes, connect() supports a shorthand syntax of passing in an object full of action creators as the second argument, but there are still good use cases for passing in an actual mapDispatchToProps function to do things yourself (especially if your dispatch prep relies on the actual prop values in some way).

    You might want to refer to the API docs for `connect().

    0 讨论(0)
  • 2021-02-07 07:47

    connect() will automatically bind dispatch to your actions if they are passed in as an object of function names.

    So no, you don't need to implement mapStateToProps. Instead you can just pass you actions like this:

    export default connect((state) => state, {
      action1,
      action2,
    })(MyComponent);
    
    0 讨论(0)
提交回复
热议问题