我从API中获取一些值并在我的状态管理中设置这个值。但是在第一次加载时只加载我设置的initialState,而不从我的api中返回值。但是当我重新加载页面时,我的值出现了。我如何解决这个问题,我的错误是什么?
这是我在Slice.js中的通知
import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import axios from "axios";
import thunkMiddleware from "redux-thunk";
export const getNotification = createAsyncThunk(
"notification/getNotification",
async () => {
var data = JSON.stringify({
.....
});
const res = await axios
.post(
"https://....",
data,
{
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
}
)
);
const notificationSlice = createSlice({
name: "notification",
initialState: {
notification: [{ id: 0 }],
loading: false,
},
extraReducers: (builder) => {
builder
.addCase(getNotification.pending, (state, action) => {
state.loading = true;
})
.addCase(getNotification.fulfilled, (state, action) => {
state.loading = false;
state.notification= action.payload;
})
.addCase(getNotification.rejected, (state, action) => {
state.loading = false;
});
},
});
export default notificationSlice.reducer;
我将此代码添加到我的app.js
function App() {
const dispatch = useDispatch();
const [width, setWidth] = useState(window.innerWidth);
const updateDimensions = () => {
setWidth(window.innerWidth);
};
useEffect(() => {
dispatch(getNotification());
}, []);
return (
<Routes>
<Route path="/homepage" element={<HomePage />} />
<Route path="/" element={<LoginUp />} />
<Route path="/" element={<PrivateRoute />}>
<Route
path="/"
element={width < 768 ? <MobileDashboard /> : <Dashboard />}
>
<Route path="dashboard" element={<MainDashboard />} />
<Route path="notification" element={<Notification />} />
</Route>
</Route>
</Routes>
);
}
export default App;
这是我的通知页面
import React, { useEffect, useState } from "react";
import { useSelector } from "react-redux";
import NotificationItem from "../components/NotificationItem";
import { Link, useLocation } from "react-router-dom";
export default function Notification() {
const {notification} = useSelector(state=>state.notification)
return (
<div className="notificationBodyWrapper">
{notification.map((el) => {
return (
<Link
to={{ pathname: "" }}
state={{ id: el.id }}
className="notificationItem"
>
<NotificationItem key={el.id} props={el} />
</Link>
);
})}
</div>
);
}
1条答案
按热度按时间wrrgggsh1#
由于您正在App.js中调用
dispatch(getNotification());
,因此也将此const {notification} = useSelector(state=>state.notification)
添加到App.js,并将通知作为prop发送到<Route path="notification" notification={notification} element={<Notification />} />
然后在通知组件中以这种方式捕获通知数据。
export default function Notification({notification}) {
将其用作源。或在通知组件中移动调用
dispatch(getNotification());
。