当我在promise解析后尝试调用回调时,我遇到了这个问题(使用.then)事实证明,这给了我的const 请求某种不同的承诺,即reducer返回为undefined:
动作:
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'中的回调(它在组件内创建另一个动作调用)。不幸的是,我收到错误,在reducer const data = action.payload.data 是未定义的。
当我不使用这个回调时,一切正常,但是我只能在这个reducer返回新状态后调用该回调。
答案 0 :(得分:2)
使用其他回调的最佳方法是将中间件“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;
}
答案 1 :(得分:1)
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))