我在 React 项目中使用 reduxjs 工具包,我尝试使用 createAsyncThunk 获取 api,但出现错误:
Cannot read properties of undefined (reading 'length')
首先它正确加载并获取数据,但刷新后我收到错误
减速器:menuSlice.js
import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import axios from "axios";
import Cookies from "universal-cookie";
const cookies = new Cookies();
const title=cookies.get('title')
const token=cookies.get('token')
export const fetchMenu = createAsyncThunk(
"getMenuItems/title",
async () => {
let url = `https://xxxxxxxx/getMenuItems/${title}`;
let data = await axios.get(url, {
headers: { Authorization: `Bearer ${token}` },
});
return data.data;
}
);
export const menuSlice = createSlice({
name: "menu",
initialState: {
menu: [],
status: false,
},
extraReducers: {
[fetchMenu.pending]: (state, action) => {
state.status = true;
},
[fetchMenu.fulfilled]: (state, action) => {
state.status = false;
state.menu = action.payload;
},
[fetchMenu.rejected]: (state, action) => {
state.status = false;
},
},
});
export default menuSlice.reducer
主页:
const title = cookies.get("title");
const token = cookies.get("token");
useEffect(() => {
dispatch(fetchMenu());
}, []);
if (status) {
return <div>...Loading</div>;
}
return (
<div className="row d-flex w-100 h-100 justify-content-center mx-auto px-0 ">
<div className="row d-flex col-md-9 col-lg-9 justify-content-center col-sm-12 mx-auto px-0">
<div className="col-md-5 col-lg-5 col-sm-12">
<Menu siteData={menu} siteId={title} />
</div>
<div className="col-md-7 col-lg-7 col-sm-12 bg-light "><Edit siteData={menu} siteId={title} /></div>
</div>
<div className="col-md-3 col-lg-3 col-sm-12 ">
<input onClick={logOut} type="button" name="" id="" value="LogOut" />
</div>
</div>
);
我在菜单组件中加载菜单状态
我猜问题与
status
有关。在你的menuSlice中initialState中的status
是false,这就是为什么在组件渲染时,这段代码将被忽略:
if (status) {
return <div>...Loading</div>;
}
如果依赖
menu
状态会更好。您可以将代码稍微更改一下:
initialState: {
menu: null,
status: false,
},
然后:
return (
menu && (
<div className="row d-flex w-100 h-100 justify-content-center mx-auto px-0 ">
<div className="row d-flex col-md-9 col-lg-9 justify-content-center col-sm-12 mx-auto px-0">
<div className="col-md-5 col-lg-5 col-sm-12">
<Menu siteData={menu} siteId={title} />
</div>
<div className="col-md-7 col-lg-7 col-sm-12 bg-light "><Edit siteData={menu} siteId={title} /></div>
</div>
<div className="col-md-3 col-lg-3 col-sm-12 ">
<input onClick={logOut} type="button" name="" id="" value="LogOut" />
</div>
</div>
)
);
因此,如果菜单确实存在,则组件将呈现。 希望有帮助。