我在我的 react-native
移动应用程序中使用 redux
。
与后端的通信是通过使用 socket.io
的 websockets 进行的。
我组织项目的方式是我有一个文件(你可以称它为对象)来初始化套接字客户端。
处理程序已注册到它,我想将操作发送到 reducers
。
socket.js
:
export function createSocket (url) {
console.log(`connecting to ${url}`)
// dispatch(actions.CONNECT)
return io(url)
}
如何从任何 React 组件
之外的那些函数调度
操作?
最佳答案
如果您在启动时初始化套接字客户端,只需将您的 redux 存储传递到函数中,然后使用 store.dispatch()
export function createSocket (url, store) {
console.log(`connecting to ${url}`)
store.dispatch(actions.CONNECT)
return io(url)
}
如果不是在启动时,那么你的套接字创建应该由一些用户操作(或类似的东西)触发,在这种情况下你应该能够使用 redux-thunk
获得对调度函数的引用> 中间件:
//the action returns a function, which gets called with store.dispatch as an argument
const myAction = someArg => dispatch => {
createSocket(url, dispatch);
};
关于javascript - 如何在组件外调度 redux Action ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50787747/