4

当我在承诺解决后尝试调用回调时遇到了这个问题(使用.then)事实证明,这给了我的 const请求某种不同的承诺,reducer 返回为未定义:

行动:

   export function lookup(company, callback) {
      const id = company.textfield;
      const url = `${ROOT_URL}${id}`;

      const request = axios.get(url)
       .then(() => callback())

      return {
        type: LOOK_UP,
        payload: request,
        meta: id
     };
 }

减速器:

import { LOOK_UP } from '../actions/index';

export default function(state = {}, action) {
    switch (action.type) {
        case LOOK_UP:
            const data = action.payload.data;
            const id = action.meta;

            if (data.Success === true) {
                return { ...state, [id]: data.CompanyInformation };
            } else {
                return state;
            }
    }
    return state;
}

如您所见,我将 axios 获取的 API 中的数据传递给我的 reducer。在此之后,我设置了状态,我需要调用“actions”中的回调(它会在组件内创建另一个动作调用)。不幸的是,我收到错误,即减速器const data = action.payload.data未定义。

当我不使用此回调时,一切正常,但情况是我需要仅在此减速器返回新状态后才调用该回调。

4

2 回答 2

3

使用另一个回调的最佳方法需要将中间件“redux-promise”替换为“redux-thunk”

import ReduxThunk from 'redux-thunk'
const store = createStore(applyMiddleware(ReduxThunk));

行动:

export function lookup(company, callback) {
  const id = company.textfield;
  const url = `${ROOT_URL}${id}`;


  return function(dispatch) { 
        axios.get(url)
       .then((res) => {
            dispatch({ type: LOOK_UP, payload: res,  meta: id });
            callback();
         )
      };
 }

减速机:

import { LOOK_UP } from '../actions/index';

export default function(state = {}, action) {
    switch (action.type) {
        case LOOK_UP:
            const data = action.payload.data;
            const id = action.meta;

            if (data.Success === true) {
                return { ...state, [id]: data.CompanyInformation };
            } else {
                return state;
            }
    }
    return state;

}

于 2018-03-07T12:08:20.397 回答
2

request等于整个语句:

const request = axios.get(url)
   .then(() => callback())

因此,如果callback()没有返回任何东西,那么承诺将解决为空。我假设你正在通过这个调用获取一些数据,所以你需要传递这些数据,否则你的 reducer 永远不会得到它。像这样:

const request = axios.get(url)
   .then((dataFromRequest) => { 
     callback(); 
     return dataFromRequest; 
});

或者您可以将两者分开并编写如下内容:

const request = axios.get(url);
request.then(() => callback());

return {
    type: LOOK_UP,
    payload: request,
    meta: id
 };

比较以下代码段中的承诺:

const promisedData = () => Promise.resolve(42);

promisedData()
  .then(data => console.log('Resolved data is ', data));


const promisedTrasformedData = () => 
   Promise.resolve(700)
   .then(data => data - 34);
   
   
promisedTrasformedData()
  .then(transformedData => console.log('Transformed data is ', transformedData));
  
  

const promisedAndLostData = () => 
  Promise.resolve(42)
 .then(data => returnNoting())

function returnNoting() { };

promisedAndLostData()
 .then(lostData => console.log('Lost data: ', lostData))

于 2017-09-12T19:31:00.307 回答