小编典典

如何在组件外部调度redux动作?

reactjs

reduxreact-native移动应用中使用。
与后端的通信是通过websockets使用进行的socket.io

我以一种可以初始化套接字客户端的文件(可以将其称为对象)的方式组织项目。
处理程序已注册到它,我想将操作发送到reducers

socket.js

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

我该如何dispatch从其他功能之外采取行动react component


阅读 356

收藏
2020-07-22

共1个答案

小编典典

如果您在启动时初始化套接字客户端,只需将您的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);
};

有关详细信息,请参见https://github.com/reduxjs/redux-
thunk

2020-07-22