2017-06-12 24 views
0

我需要从我的redux应用的外侧调用redux动作,就像在外部js文件中一样。我有一个处理REST请求的api.js文件,我需要的只是在成功响应中调用一个动作,并由我的中间件执行处理动作。从redux的外侧调用动作

proplem是我无法访问存储或在api.js文件中发送,即使我出口我的商店因为它没有连接到REDX或任何反应组件。

api.js

function ApiRequest(url) { 
    return fetch(thisUrl) 
     .then(async (rawRes) => { 
      if (rawRes && rawRes.status === 200) { 
       // <------- Here i wanna run redux action 
      } 

     }) 
     .catch((err) => { 
      console.log(err) 
     }); 

} 

apiMiddleware:

const apiMiddleware = store => next => (action) => { 
    switch (action.type) { 
    case 'API_SUCCESS_RESPONSE' : 
     console.log('action success executed') 
     break; 

    default : 
    } 
    return next(action); 
}; 

export default apiMiddleware; 

什么建议吗?

回答

1

基本上,如果您有权访问商店,则可以在任何时候发送操作。

所以解决您的问题归结为“我怎么提供ApiRequest内进入店内变量?有这个问题许多解决方案。一个全局变量分配storeWindow是最简单的。

但是,全局解决方案最终会遇到隐式排序问题(商店必须在ApiRequest之前初始化)以及其他问题

例如,假设您在创建redux存储库时指定window.store = store,那么您的代码看起来像这个:

function ApiRequest(url) { 
    return fetch(thisUrl) 
     .then(async (rawRes) => { 
      if (rawRes && rawRes.status === 200) { 
       store.dispatch({type: 'API_SUCCESS_RESPONSE' })` 
      } 

     }) 
     .catch((err) => { 
      console.log(err) 
     }); 

} 

编辑:为了清楚,从你的问题apiMiddleware不是的商店。 ApiMiddleware是一个给已经创建的商店的函数,将它包装在中间件中。您的程序中有代码,如下所示:

import { createStore } from 'redux' 
export apiMiddleware from './apiMiddleware' 
const store = createStore(reducers, apiMiddleware) 

然后^^^这是您要全球导出的商店。

+0

谢谢你,这正是我想要的,但不幸的是,我在反应原生应用程序中使用了REDX,所以我不这么认为有任何窗口变量可以使用,任何建议? – N3TC4t

+0

查看https://stackoverflow.com/questions/35577551/how-to-use-global-variables-in-react-native/35577584 – AnilRedshift

+0

全球是类似的反应本地窗口,所以所有想要的是global.dispatch = store。调度 – N3TC4t

相关问题