是否可以从组件外部触发 Redux 操作? [英] Is it possible to trigger a Redux action from outside a component?

查看:40
本文介绍了是否可以从组件外部触发 Redux 操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个 React 应用程序并正在调用一个自定义处理程序库来调用我们的 REST API.

I'm building a React app and am calling a custom handler library to make calls to our REST API.

在这些(非 React)函数中,我想触发 Redux 操作以使用端点响应更新存储,但无法弄清楚如何在没有通常的 'mapDispatchToProps'/connect() 方法.

Within these (non-React) functions, I'd like to trigger Redux actions to update the store with the endpoint response, but can't figure out how to trigger the Redux action without the usual 'mapDispatchToProps'/connect() method.

这可能吗?

谢谢

推荐答案

为了从 React.Component 你需要获取 store 实例并调用 dispatch 就像

In order to dispatch and action from outside of the scope of React.Component you need to get the store instance and call dispatch on it like

import { store } from '/path/to/createdStore';
​
function testAction(text) {
  return {
    type: 'TEST_ACTION',
    text
  }
}
​
store.dispatch(testAction('StackOverflow'));

这篇关于是否可以从组件外部触发 Redux 操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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