Привет, я новичок в использовании redux, и я не могу понять, почему FetchUsers () не работает в диспетчере и пользователях, которых я получаю в приложении. js - всегда пустой массив. useDispatch ()? или добавляется другое промежуточное ПО?
reducer
import {
FETCH_USERS,
FETCH_USERS_SUCCESS,
FETCH_USERS_FAILURE,
} from "../actions/types";
const initialValues = {
loading: false,
users: [],
error: "",
};
const usersreducer = (state = initialValues, action) => {
switch (action.type) {
case FETCH_USERS:
return { ...state, loading: true };
case FETCH_USERS_SUCCESS:
return { ...state, loading: false, users: action.payload };
case FETCH_USERS_FAILURE:
return { ...state, loading: false, error: action.payload };
default:
return state;
}
};
действия:
import { FETCH_USERS, FETCH_USERS_FAILURE, FETCH_USERS_SUCCESS } from "./types";
const fetchUsersRequest = () => {
return {
type: FETCH_USERS,
};
};
const fetchUsersFailure = (error) => {
return {
type: FETCH_USERS_FAILURE,
payload: error,
};
};
const fetchUsersSuccess = (users) => {
return {
type: FETCH_USERS_SUCCESS,
payload: users,
};
};
export const FetchUsers = () => {
return (dispatch) => {
dispatch(fetchUsersRequest());
fetch("https://jsonplaceholder.typicode.com/users")
.then((res) => {
const users = res.data;
dispatch(fetchUsersSuccess(users));
})
.then((err) => {
const error = "error";
dispatch(fetchUsersFailure(error));
});
};
};
индекс:
import { createStore, applyMiddleware } from "redux";
import { Provider } from "react-redux";
import thunk from "redux-thunk";
import rootReducer from "./reducers";
const store = createStore(rootReducer, applyMiddleware(thunk));
ReactDOM.render(
<Provider store={store}>
<React.StrictMode>
<App />
</React.StrictMode>
</Provider>,
document.getElementById("root")
);
Приложение js:
import { FetchUsers } from "./actions/actions";
import { useSelector, useDispatch } from "react-redux";
const App = () => {
const users = useSelector((state) => state.users);
useEffect(() => {
FetchUsers();
console.log(users.users);
}, []);
..................... .................................................. .................................