我如何从 React Native 中的辅助函数中调度一个动作

use*_*472 5 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;
Run Code Online (Sandbox Code Playgroud)

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

我尝试过action.js像这样创建一个动作名称

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

在减速器中:

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

helper.js并像这样调用它

内部HTTPRequest函数

helloWorld();
Run Code Online (Sandbox Code Playgroud)

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

谁能告诉我该如何处理这个问题。?

Piy*_*ngh 2

我假设你已经安装了 redux-thunk。

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

const HTTPRequest = (path, body, method = 'POST',
                      authorizedToken = null,dispatch,actionCreator) => {
Run Code Online (Sandbox Code Playgroud)

然后,在 axios 调用成功后,您可以添加以下行

 dispatch(actionCreator.success(response))
Run Code Online (Sandbox Code Playgroud)

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

 dispatch(actionCreator.failure(error.message))
Run Code Online (Sandbox Code Playgroud)

在 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)
 }
}
Run Code Online (Sandbox Code Playgroud)

创建操作创建器并将其作为参数传递给 helper.js 文件中提供的 HTTPREQUEST 实用程序。现在,根据成功和失败响应,它正在启动操作。使用该操作,您可以将响应存储在 redux 存储中,然后可以在组件中使用它。

下面更新了答案以解决确切的问题。否则我会推荐上面的解决方案。尝试这个

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

store.subscribe(func)
Run Code Online (Sandbox Code Playgroud)