简体   繁体   English

如何在调度到减速器之前从操作中调用 function?

[英]How to call a function from action before dispatching to reducer?

I am working on a React Redux app.我正在开发一个 React Redux 应用程序。 I have an action in which I am calling a utility function before dispatching the action.我有一个动作,我在调度动作之前调用实用程序 function。

import GetDataFromAPIs from "../utils/menu-creator";
export const UPDATE_DATA = 'UPDATE_DATA';

export const updateData = () => {
    const newData = GetDataFromAPIs();

    return{
        type: UPDATE_DATA, 
        payload: newData
    };
};

And, here is what GetDataFromAPIs.js is loosely doing:而且,这就是 GetDataFromAPIs.js 正在做的事情:

import React from "react";
import axios from "axios";

const apiOneData = axios.get('/api/a');
const apiTwoData = axios.get('/api/b');


const GetDataFromAPIs = () => {
    axios.all([apiOneData, apiTwoData]).then(axios.spread((...responses) => {
        var firstDataSet = responses[0].data
        var secondDataSet = responses[1].data;
        var dataObject = [];

        dataObject.push(firstDataSet);
        dataObject.push(secondDataSet);

        return dataObject;

    })).catch(errors => {
        console.log("There was an error.");
    })
}

export default GetDataFromAPIs;

But when the application runs newData is set as undefined .但是当应用程序运行时newData被设置为undefined I am trying to step through GetDataFromAPIs.js but it traces till axios.all and then breaks out of the function.我正在尝试逐步执行 GetDataFromAPIs.js,但它一直跟踪到 axios.all,然后突破 function。 I don't see any error in the console.我在控制台中看不到任何错误。

So what I am guessing is that action is dispatched before the two axios.all is resolved.所以我猜是在两个 axios.all 解决之前调度了动作。 I thought this would be synchronous (newData will get the data back and then the action will be dispatched).我认为这将是同步的(newData 将取回数据,然后分派操作)。 Am I doing this wrong?我做错了吗?

You need to explicitly tell the action to wait to get that data asynchronously.您需要明确告诉操作wait异步获取该数据。 To do that, make the following changes:为此,请进行以下更改:


Your GetDataFromAPIs function should look this this:您的GetDataFromAPIs function 应该是这样的:

const GetDataFromAPIs = async () => {
    // everything in here stays the same
}

And your updateData function should look like this:您的updateData function 应该如下所示:

export const updateData = async (dispatch) => {
    const newData = await GetDataFromAPIs();

    return dispatch({
        type: UPDATE_DATA, 
        payload: newData
    });
};

Be sure to dispatch your action.请务必dispatch您的操作。

Note:笔记:

If you haven't got redux-thunk setup then you'll need to install that npm module and update your createStore to look something like this:如果你还没有redux-thunk设置,那么你需要安装npm模块并将你的createStore更新为如下所示:

// other imports
import { applyMiddleware, createStore } from 'redux'
import thunk from 'redux-thunk'

const store = createStore(rootReducer, applyMiddleWare(thunk))

I think async/await is what you need.我认为async/await是你需要的。

export const updateData = async () => {
    const newData = await GetDataFromAPIs();

    return{
        type: UPDATE_DATA, 
        payload: newData
    };
};


const GetDataFromAPIs = async () => {
  try {
    const responses = await axios.all([apiOneData, apiTwoData]).then(axios.spread((...responses);
    var firstDataSet = responses[0].data
    var secondDataSet = responses[1].data;
    var dataObject = [];

    dataObject.push(firstDataSet);
    dataObject.push(secondDataSet);

    return dataObject;

  } catch(errors) {
      console.log("There was an error.");
  })
}

GetDataFromApis doesn't return. GetDataFromApis不返回。

You should do你应该做

const GetDataFromApis = async () => {
    return axios.all(...

GetDataFromApis will also return a Promise so you should await it in updateData like so: GetDataFromApis还将返回Promise所以你应该在updateDataawait它,如下所示:

export const updateData = async () => {
    const newData = await GetDataFromAPIs();

    return {
        type: UPDATE_DATA, 
        payload: newData
    };
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM