当我在 promise 解决后尝试调用回调时遇到了这个问题(使用 .then)事实证明这给我的 const request 某种不同的 promise 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
};
}
reducer :
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。在此之后,我设置了状态,我需要调用“ Action ”中的回调(它会在组件内部创建另一个 Action 调用)。不幸的是,我在 reducer 中遇到错误 const data = action.payload.data 未定义。
当我不使用此回调时,一切正常,但情况是我需要仅在此 reducer 返回新状态后调用该回调。
最佳答案
在操作中使用另一个回调的最佳方法需要将中间件“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();
)
};
}
reducer :
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;
关于javascript - 使用 redux-promise 和 axios 时 Reducer 返回 undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46183617/