【问题标题】:How to update UI after 2 seconds after showing Loading and using setTimeout in createAsyncThunk如何在 createAsyncThunk 中显示加载和使用 setTimeout 后 2 秒后更新 UI
【发布时间】:2022-11-11 22:52:25
【问题描述】:

在显示加载 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;

在上面的文件之后,我在家庭组件中尝试了这个,但它不起作用 我在盘子/已完成操作的有效负载中没有得到正确的值 在 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 (...)
}

现在它正在按预期呈现 ui。首先显示加载... 2秒然后显示主页但现在这里的问题是 redux 操作不断被调用,它正在使内存过载。就像它正在加载一样,它应该显示待处理,一旦加载,它应该显示已满,但未决和已满循环持续进行

【问题讨论】:

    标签: reactjs redux redux-toolkit


    【解决方案1】:

    该函数不会返回承诺。请像这样更新。

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

    【讨论】:

    • 它不工作。在 redux devtools 中,action 不断地被调度。并且 Ui 只卡在加载
    • 如果我返回任何字符串或其他东西并且它正在被填满,它工作正常。但是一旦通过 DISHES 对象数组,它就会进入挂起和填充的连续循环。不知道为什么。休息它工作正常,正如你所建议的那样。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-23
    • 1970-01-01
    • 2015-12-10
    • 1970-01-01
    • 2020-04-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多