为了账号安全,请及时绑定邮箱和手机立即绑定

我如何从 React Native 中的辅助函数分派动作

我如何从 React Native 中的辅助函数分派动作

qq_笑_17 2021-06-30 16:01:18
我有一个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;现在,我面临的问题是,我如何从这个辅助函数中分派一个动作,或者我如何user token从 redux 存储中获取。并helper.js像这样调用它内部HTTPRequest功能helloWorld();我只能看到日志Hello world has been dispatched,但我没有看到调度员的任何日志。谁能告诉我如何处理这个问题。?
查看完整描述

2 回答

?
三国纷争

TA贡献1804条经验 获得超7个赞

我假设您已经安装了 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)

 }

}

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


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


import store from './redux/store.js';

Const func=()=> {}


store.subscribe(func)


查看完整回答
反对 回复 2021-07-08
?
牛魔王的故事

TA贡献1830条经验 获得超3个赞

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


在helper.js我已经导入了商店,现在辅助函数看起来像这样


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>

}

这是因为 store 是一个对象,它几乎没有方法,包括调度这里提到的动作。


查看完整回答
反对 回复 2021-07-08
  • 2 回答
  • 0 关注
  • 181 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信