在我的操作中,我从服务器接收到JSON响应,然后在reducer中设置了SET_CURRENT_STORAGE。在第二次调度中,我正在处理第一个操作的结果,并尝试使用名为getStorageCapacity()
的自定义函数来设置有效负载。
以下是我的操作代码
export function fetchStorage() {
return function(dispatch) {
return fetch('/api/dashboard/storage', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include'
})
.then(response => response.json().then(body => ({ response, body })))
.then(({ response, body }) => {
//calculate storage
if (!response.ok) {
} else {
var test1 = body.value;
var take1 = Promise.resolve(
dispatch({
type: 'SET_CURRENT_STORAGE',
payload: body.value
})
);
take1.then(function() {
dispatch({
type: 'SET_CURRENT_STORAGE_CAPACITY',
payload: getStorageCapacity(test1)
});
});
}
});
};
}
export function getStorageLevel(payload) {
return 'High';
}
export function getStorageCapacity(test1) {
console.log('reached ' + test1);
var arr = [];
for (var key in test1) {
console.log(test1[key]);
}
test1.forEach((item, i) => {
console.log(item.capacity);
return item.capacity;
});
}
export function getStorageAvailable(payload) {
return '150';
}
export function getStorageUsed(payload) {
return '10';
}
下面是我的减速器代码
import {
SET_CURRENT_STORAGE,
SET_CURRENT_APPLICATION_SERVICES,
SET_CURRENT_STORAGE_LEVEL,
SET_CURRENT_STORAGE_CAPACITY,
SET_CURRENT_STORAGE_AVAILABLE,
SET_CURRENT_STORAGE_USED
} from '../actions/typesActions';
import isEmpty from '../validation/is-empty';
const initialState = {
storageValue: [],
storageLevel: 'Low',
storageCapacity: '60',
storageAvailable: '50',
storageUsed: '10',
appSerStatus: []
};
export default function(state = initialState, action) {
console.log(state);
switch (action.type) {
case SET_CURRENT_STORAGE:
return {
...state,
storageValue: action.payload
};
case SET_CURRENT_APPLICATION_SERVICES:
return {
...state,
appSerStatus: action.payload
};
case SET_CURRENT_STORAGE_LEVEL:
return {
...state,
storageLevel: action.payload
};
case SET_CURRENT_STORAGE_CAPACITY:
console.log(action);
return {
...state,
storageCapacity: action.payload
};
case SET_CURRENT_STORAGE_AVAILABLE:
return {
...state,
storageAvailable: action.payload
};
case SET_CURRENT_STORAGE_USED:
return {
...state,
storageUsed: action.payload
};
default:
return state;
}
}
每当我使用foreach进行处理时,它都会以 undefined 的形式返回,但是当我对getStorageCapacity()
中的返回值进行硬编码时,该值将按预期返回。
你知道是什么原因吗?**
答案 0 :(得分:0)
从forEach中返回并不会返回到函数getStorageCapacity
,而是返回到循环之外。
也许您想尝试这样的事情:
export function getStorageCapacity(test1) {
console.log('reached ' + test1);
var arr = [];
for (var key in test1) {
console.log(test1[key]);
}
arr = test1.map((item, i) => {
console.log(item.capacity);
return item.capacity;
});
return arr;
}
答案 1 :(得分:0)
return value from forEach is undefined
.forEach()函数应该继续循环-它会忽略函数的返回值。