我如何在React Native中从助手功能中调度动作

时间:2019-06-19 13:09:14

标签: javascript reactjs react-native redux react-redux

我有一个helper.js文件,其中包含所有帮助程序功能,包括带有axios的HTTP请求处理程序。这是我的helper.js文件代码:

const HTTPRequest = (path, body, method = 'POST', authorizedToken = null) => {
    return new Promise((resolve, reject) => {
        let headers = {
            'Content-type': 'multipart/form-data',
        };

        // Set authorization token
        if (authorizedToken) {
            headers['Authorization'] = "JWT " + authorizedToken;  // Here i want to get user token from the redux store not though passing the token

        }

        const fulHeaderBody = {
            method,
            headers,
            timeout: 20,
            url: path
        };


axios(fulHeaderBody).then(response => {
            if (response.success) {
                resolve(response);
            } else {

                // Show toast about the error
                Toast.show({
                    text: response.message ? response.message : 'Something went wrong.',
                    buttonText: 'Okay',
                    type: 'danger'
                });
                resolve(response);
            }
        }).catch(error => {
            if (error.response) {

               if(error.response.status === 401){
                    // I WANT TO DISPATCH AN ACTION HERE TO LOGOUT CLEAR ALL STORAGE DATA IN REDUX AND CHANGE THE STATE TO INITIAL
               }else{
                    console.log('Error', error.message);
               }
            }  else {
                // Something happened in setting up the request that triggered an Error
                console.log('Error', error.message);
            }
            console.log(error.config);
            reject(error);
        })
    });
};
export default HTTPRequest;

现在,我面临的问题是,如何从该辅助函数中调度动作,或者如何从redux存储中获取user token

我尝试像这样在action.js中创建动作名称

export function helloWorld() {
    console.log('Hello world has been dispatched');
    return function(dispatch){
        dispatch(helloWorldDispatch());
    }
}
function helloWorldDispatch() {
    return {
        type: 'HELLO_WORLD'
    }
}

和在减速器中:

switch (action.type) {
    case 'HELLO_WORLD': {
        console.log('Hello world Current state',state);
        return state
    }
    default:
        return state
}

然后像这样从helper.js调用

内部HTTPRequest函数

helloWorld();

我只能看到日志Hello world has been dispatched,但是看不到调度程序的任何日志。

任何人都可以告诉我该如何处理。 ?

2 个答案:

答案 0 :(得分:2)

我认为您已经安装了redux-thunk。

首先,您需要在helper.js中修改您的 HTTPRequest 函数。向其添加两个参数,如下所示:调度

const HTTPRequest = (path, body, method = 'POST',
                      authorizedToken = null,dispatch,actionCreator) => {

然后在您的axios呼叫成功后,您可以在行下方添加

 dispatch(actionCreator.success(response))

对于失败,您可以如下添加

 dispatch(actionCreator.failure(error.message))

在action.js文件中创建操作为

export const helperAction=(path, body, method = 'POST',
                      authorizedToken = null) =>{
var actionCreator = {}
actionCreator.success = helloWorld
actionCreator.failure = failureFunction //your failure action

return dispatch => {
  HTTPRequest(path, body, method = 'POST',
                      authorizedToken = null,dispatch, actionCreator)
 }
}

创建动作创建者,并将其作为参数与调度一起传递给helper.js文件中可用的HTTPREQUEST实用程序。现在,基于成功和失败的响应,它开始执行操作。使用该操作,您可以将响应存储在redux存储中,然后可以在组件中使用它。

下面更新的答案可以解决确切的问题。否则,我会建议上述解决方案。  试试这个

import store from './redux/store.js';
Const func=()=> {}

store.subscribe(func)

答案 1 :(得分:0)

在评论中有@Avin Kavish共享的链接,这是我的解决方案。

import {store} from "../redux/ConfigureStore"; //I have imported my store const HTTPRequest = (path, body, method = 'POST', authorizedToken = false) => { let getInitialStates = store.dispatch(helloWorld()); //This to dispatch an action <ALL OTHER CODES AS ABOVE HERE> } 中,我已经导入了商店,现在助手功能看起来像这样

<RelativeLayout
    android:layout_width="100dp"
    android:layout_height="wrap_content">

<ImageView
    android:id="@+id/header_icon"
    android:layout_width="48dp"
    android:layout_height="48dp"
    android:layout_marginTop="20dp"/>

<TextView
    android:id="@+id/header_label"
    android:layout_width="140dp"
    android:layout_below="@id/header_icon"
    android:layout_centerHorizontal="true"
    android:layout_height="wrap_content"/>

</RelativeLayout> </android.support.v17.leanback.widget.NonOverlappingLinearLayout>

这是因为商店是一个对象,它几乎没有方法,包括调度动作here