Reactjs Redux操作返回未定义
因此,我正在使用React Native和Redux构建一个费用应用程序,我有两个操作:Reactjs Redux操作返回未定义,reactjs,redux,redux-thunk,Reactjs,Redux,Redux Thunk,因此,我正在使用React Native和Redux构建一个费用应用程序,我有两个操作: export const getExpenses = () => async (dispatch) => { await db.onSnapshot((querySnapshot) => { const data = []; querySnapshot.forEach((doc) => { const { description, name, valu
export const getExpenses = () => async (dispatch) => {
await db.onSnapshot((querySnapshot) => {
const data = [];
querySnapshot.forEach((doc) => {
const { description, name, value, date, type } = doc.data();
data.push({
key: doc.id,
doc, // DocumentSnapshot
description,
date,
name,
value,
type,
});
});
dispatch({
type: TYPES.GET_EXPENSES,
payload: data,
});
dispatch({
type: TYPES.SET_LOADING_EXPENSES,
payload: false,
});
console.log('getExpenses', data);
});
};
export const filterMonthInfo = () => async (dispatch, getState) => {
const info = getState().monthExpenses.data; // data returned by getExpenses()
const currentMonth = getState().dateReducer.currentDate;
const filteredInfo = info
.filter(
(data) => moment(moment(data.date).format('DD/MM/YYYY')).format('MMMM YYYY') === currentMonth,
)
.sort((a, b) => new Date(b.date) - new Date(a.date));
dispatch({
type: TYPES.GET_FILTERED_EXPENSES,
payload: filteredInfo,
});
console.log('filtermonth', filteredInfo);
};
在要使用filterMonthInfo返回的数据的屏幕中,我有以下useEffect:
useEffect(() => {
getExpenses();
filterMonthInfo();
getCurrentDate();
}, []);
但由于getExpenses是一个异步函数,filterMonthInfo将首先运行并返回undefined,因为最后一个函数是基于getExpenses返回的数据进行过滤的。
让我先运行getExpenses,然后再运行filterMonthInfo的最佳方法是什么
谢谢如果要在异步调用完成后运行代码,必须使用Promise等待。将代码编写为
useEffect(() => {
getExpenses()
.then(()=>{
filterMonthInfo();
getCurrentDate();
}
);
}, []);
或者使用async await,因为它使语法更加清晰