问题
All around the web I see code dispatching directly from the component via this.props.dispatch passed in from the connect function from react-redux. My question is: why not simply dispatch directly from the actions file instead of just returning an action object back into the component and dispatching from there? I feel like I'm missing something here. It feels a bit wrong to dispatch directly from the component like that when we can simply call a function, pass in what's needed, and let the action creator do the dispatching for us outside of our react component.
Here's a brief example of what I mean: https://gist.github.com/overthemike/5481dab563c7f97f4151ab1c8c9cb4f1
What am I missing?
回答1:
That's really just one way to do it. Gotta choose what you like better and suits your code style.
They way I like the most is like this, with ES6:
import { actionA, actionB } from 'path/to/redux/actions'
class MyComponent extends React.Component { ... }
const mapStateToPros = {...}
const mapDispatchToProps = { actionA, actionB }
export default connect(mapStateToPros, mapDispatchToProps)(MyComponent)
By using shorthand notation for mapDispatchToProps, MyComponent will receive functions actionA and actionB as props, and can be called with this.props.actionA. const mapDispatchToProps = { actionA, actionB } will be interpreted by redux as:
const mapDispatchToProps = (dispatch) => {
return {
actionA: (...args) => {dispatch(actionA(...args))},
actionB: ...,
}
}
So calling this.props.actionA() is actually calling dispatch(actionA())
回答2:
You can certainly call this.props.dispatch() directly in a connected component. However, I prefer to keep my React components "unaware" of Redux by not referring to dispatch directly, and having them call other functions as props. That way, the component doesn't know or care if the function was a bound Redux action creator, a callback from a parent, or a mock function in a test.
As @cfraser said, I highly recommend using the "object shorthand" syntax for passing action creators to connect.
You may be interested in my post Idiomatic Redux: Why Use Action Creators?, which goes into more details on the topic.
Per your comment about traceability: you would step backwards from the action creator being passed to the component, to the action creator definition, to the action type, to the reducers which respond to that action type.
来源:https://stackoverflow.com/questions/46460328/why-dispatch-in-a-component-instead-of-an-action-file