如何在redux工具包中正确存储action.payload



我正在使用redux工具包从API获取用户,并将用户的状态保存在商店中。

userStore: {
users: [],
loading: true
}
}

这显示在firefox中的redux工具包开发工具中。

我原以为会的。

userStore: {
users: Array[..], //an array of 10 users
loading: false
}
}

我已经在index.js 中配置了商店

const store = configureStore({
reducer: {
userStore: usersReducer,
},
});
export default store;

userSlice.js


const initialState = {
users: [],
loading: false,
};
export const userSlice = createSlice({
name: 'users',
initialState,
reducers: {
receivedUserList: (state, action) => {
state.users = action.payload;
},
toggleLoadingUsers: (state) => {
state.loading = !state.loading;
},
},
});
export const { receivedUserList, toggleLoadingUsers } = userSlice.actions;
export default userSlice.reducer;

用户操作.js


export const fetchUsers = (data) => async (dispatch) => {
try {
dispatch(toggleLoadingUsers());
const response = await userAPI.get('/users');
dispatch(receivedUserList(response.data));
dispatch(toggleLoadingUsers());
} catch (error) {
console.log(error);
}
};

我在我的App.js中使用fetchusers是这样的。

const dispatch = useDispatch();
const { users, loading } = useSelector((state) => state.userStore);
useEffect(() => {
console.log('something');
console.log(loading);
console.log(users);
dispatch(fetchUsers());
}, []);

这没有正确更新状态。获取用户后如何设置状态?我已经路过商店了/src/index.js 中的store/index.js

import store from './store/index';
import { Provider } from 'react-redux';
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>,
document.getElementById('root')
);

Redux工具箱背后的理念是删除操作、类型和减少程序的样板代码,并将它们统一为一个切片。

让我们重构用户切片代码,如下所示。


import { createAsyncThunk } from "@reduxjs/toolkit";
export const fetchUsers = createAsyncThunk("users/fetchUsers", async (data) => {
const response = await userAPI.get("/users");
return response.data;
});
const initialState = {
users: [],
loading: false,
};
export const userSlice = createSlice({
name: "users",
initialState,
reducers: {
receivedUserList: (state, action) => {
state.users = action.payload;
},
toggleLoadingUsers: (state) => {
state.loading = !state.loading;
},
},
extraReducers: {
[fetchUsers.pending]: (state, action) => {
state.loading = true;
},
[fetchUsers.fulfilled]: (state, action) => {
state.loading = false;
state.users = [...state.users, ...action.payload];
},
[fetchUsers.rejected]: (state, action) => {
state.loading = true;
state.error = action.error;
},
},
});
export const { receivedUserList, toggleLoadingUsers } = userSlice.actions;
export default userSlice.reducer;

然后从userSlice导入fetchUsers

//top-level import 
import {fetchUsers} from "../userSlice"

const dispatch = useDispatch();
const { users, loading } = useSelector((state) => state.userStore);
useEffect(() => {
console.log('something');
console.log(loading);
console.log(users);
dispatch(fetchUsers());
}, []);

最新更新