How to dispatch redux action outside of a component?

夙愿已清 提交于 2019-12-22 08:10:04

问题


I'm using redux in my react-native mobile app.
The communication with the backend is via websockets using socket.io.

I organize the project in a way where I have a file (you could call it an object) which initialize the socket client.
The handlers are registered to it, and I want to send actions to the reducers.

socket.js:

export function createSocket (url) {
  console.log(`connecting to ${url}`)
  // dispatch(actions.CONNECT)
  return io(url)
}

How can I dispatch actions from those functions outside of any react component?


回答1:


If you initialise the socket client at startup time, just pass your redux store into the function and then use store.dispatch()

export function createSocket (url, store) {
  console.log(`connecting to ${url}`)
  store.dispatch(actions.CONNECT)
  return io(url)
}

If not at startup, then your socket creation should be triggered by some user action (or something similar) in which case you should be able to get a reference to the dispatch function using the redux-thunk middleware:

//the action returns a function, which gets called with store.dispatch as an argument
const myAction = someArg => dispatch => {
    createSocket(url, dispatch);
};

See https://github.com/reduxjs/redux-thunk for details



来源:https://stackoverflow.com/questions/50787747/how-to-dispatch-redux-action-outside-of-a-component

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