在我的应用程序中,我使用的是 React Hooks/Context API。现在,每当我的 Provider 组件挂载时,我都需要将从 localStorage 获取的数据分配给 initialState.carts / state.carts。如果 useEffect 支持返回对象,这是可能的。但是不能在 useEffect 中返回对象!
现在我该如何解决这个问题?
代码如下,
const initialState = {
books: books,
carts: []
};
export const Context = createContext(initialState);
export const Provider = ({ children }) => {
const [state, dispatch] = useReducer(reducer, initialState);
useEffect(() => {
if (localStorage.getItem("carts") !== null) {
const fetchedCarts = JSON.parse(localStorage.getItem("carts"));
//Here I want to assign 'fetchedCarts' array items in 'state.carts' or 'initialState.carts'
}
});Run Code Online (Sandbox Code Playgroud)
如果用户未注册,API 会抛出 401。但即使有错误,extraReducers 也会执行已完成的情况。500 和其他错误也会发生这种情况。
额外减速器
extraReducers: (builder) => {
builder
.addCase(login.pending, function (state) {
console.log("pending");
state.isLoading = true;
})
.addCase(login.fulfilled, (state, action) => {
console.log("fullfield");
state.isLoading = false;
state.user = action.payload;
state.isAuthenticated = true;
})
.addCase(login.rejected, (state, action) => {
console.log("rejected");
console.log(action.payload);
state.isLoading = false;
state.error = true;
state.message = action.payload;
state.user = null;
});
}
Run Code Online (Sandbox Code Playgroud)
asyncThunk登录方法
export const login = createAsyncThunk("auth/login", async (user, thunkAPI) => {
try {
let user = await authService.login(user);
return user;
} catch (error) …Run Code Online (Sandbox Code Playgroud)