redux 如何在createAsyncThunk中显示正在加载并使用setTimeout后2秒后更新UI

xt0899hw  于 2022-11-24  发布在  其他
关注(0)|答案(1)|浏览(206)

我试图显示加载2秒后在home组件上呈现的菜肴,但无法做到这一点。我对createAsyncThunk部分有疑问。

// This is the structure of DISHES which i am importing
// DISHES = [
    {id: 0, name: "Uthappizza", image: "/assets/images/uthappizza.png", category: "mains",label: "Hot",},
    {id: 1,name: "Zucchipakoda",image: "/assets/image/zucchipakoda.png",
category: "appetizer",}]

const initialState = {
    isLoading: true,
    errMsg: null,
    dishes: [],
};
export const getDishes = createAsyncThunk("dishes/getDishes", () => {
    //return setTimeout(() => {
        //return DISHES;
    //}, 2000);
// I have tried to convert it like this
return DISHES;

//And from useEffect I am using setTimeout
});
export const dishesSlice = createSlice({
    name: "dishes",
    initialState,
    reducers: {},
    extraReducers: {
        [getDishes.pending]: (state) => {
            state.isLoading = true;
        },
        [getDishes.fulfilled]: (state, action) => {
            console.log(action);
            state.isLoading = false;
            state.dishes = state.dishes.concat(action.payload);
        },
        [getDishes.rejected]: (state) => {
            state.isLoading = false;
        },
    },
});

export default dishesSlice.reducer;

在上述文件后,我在home组件中尝试此操作,但它不起作用,我在disks/fullfilled操作上的有效负载中没有获得正确的值。在redux devtools中,操作调度成功并显示正在加载,但之后出现错误

import { getDishes } from "../redux/stateSlices/dishesSlice";

const { dishes, isLoading } = useSelector((state) => state.dishes);
const dispatch = useDispatch();
useEffect(() => {
// upadated code and using setTimeout here
       setTimeout(()=>{
         dispatch(getDishes());
      },2000)
    }, []);

if(isLoading){
return <Loading/>
}else {
return (...)
}

现在,它正在按照预期呈现用户界面。首先显示正在加载...... 2秒,然后显示主页,但现在的问题是,redux操作被不断调用,它正在超载内存。就像一个正在加载的操作一样,它应该显示pending,一旦加载,它应该显示fullfilled,但pending和fullfilled循环不断进行

bqf10yzr

bqf10yzr1#

函数不会返回承诺。请按如下方式更新。

() => {
    return new Promise((resolve)=>{
        setTimeout(() => {
           resolve(DISHES);
        }, 2000);
    });
}

相关问题