When to use store.dispatch() in my React / Redux app?

ぐ巨炮叔叔 提交于 2021-02-08 10:11:17

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!