我试图显示加载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循环不断进行
1条答案
按热度按时间bqf10yzr1#
函数不会返回承诺。请按如下方式更新。