问题
I'm using mapDispatchToProps in my React / Redux app.
function mapDispatchToProps(dispatch) {
return bindActionCreators( { fetchUsers }, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(SearchBar);
I have seen store.dispatch() being used inside containers, could I use that instead of mapDispatchToProps? I don't fully understand the store.dispatch() and where should I use it?
回答1:
This won't work if you render your app on server because you want to have different store
instance per request on server. That's why Redux
docs don't recommend this approach.
From the Docs of bindActionCreators,
You might ask: why don't we bind the action creators to the store instance right away, like in classical Flux? The problem is that this won't work well with universal apps that need to render on the server. Most likely you want to have a separate store instance per request so you can prepare them with different data, but binding action creators during their definition means you're stuck with a single store instance for all requests.
Also @Dan had a comment here suggesting to use the connect()
method himself.
回答2:
You want to use connect
and mapDispatchToProps
. Those give you access to dispatch and encapsulate the calls to dispatch in one place.
store.dispatch
is useful if you have somewhere where mapDispatchToProps
won't work, but I would avoid that as it's going to complicate your code needlessly.
来源:https://stackoverflow.com/questions/44749723/when-to-use-store-dispatch-in-my-react-redux-app