如何在组件外部发送redux动作? [英] How to dispatch redux action outside of a component?

查看:154
本文介绍了如何在组件外部发送redux动作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 react-native 移动应用中使用 redux

使用 socket.io 通过websockets与后端进行通信。

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

我组织项目的方式是我有一个文件(你可以称之为对象)来初始化套接字客户端。

处理程序注册到它,我想发送动作到 reducers

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)
}

我如何派遣来自任何 react组件之外的那些函数的行动

推荐答案

如果在启动时初始化套接字客户端,只需将redux存储区传递给函数,然后使用 store.dispatch()

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)
}

如果没有在启动时,那么你的套接字创建应该由一些用户动作(或类似的东西)触发,在这种情况下你应该能够使用 redux-thunk来获得对dispatch函数的引用中间件:

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);
};

参见 https://github.com/reduxjs/redux-thunk 了解详情

这篇关于如何在组件外部发送redux动作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆