简体   繁体   English

Redux Reselect 未从 api 获取数据

[英]Redux Reselect is not fetching the data from api

I used Redux and reselect, but I couldn't fetch data by connect function from server.我使用了 Redux 并重新选择,但无法通过connect功能从服务器获取数据。 but if I use useSelector and useEffect hooks.但是如果我使用useSelectoruseEffect钩子。 it will work correctly and fetching data successfully.它将正常工作并成功获取数据。 but I need want to use connect function instead of useSelector .但我需要使用connect函数而不是useSelector I worked project in https://codesandbox.io and the source code is in below link.我在https://codesandbox.io 中工作过项目,源代码在下面的链接中。
source code link 源代码链接
sample code is here.示例代码在这里。 Thanks a lot 😊非常感谢😊

import { createSlice } from "@reduxjs/toolkit";

import api from "./api";
const initialUser = localStorage.getItem("user")
  ? JSON.parse(localStorage.getItem("user"))
  : null;

// Slice
const slice = createSlice({
  name: "user",
  initialState: {
    user: initialUser,
    users: [],
    isLoading: false,
    error: false
  },
  reducers: {
    startLoading: (state) => {
      state.isLoading = false;
    },
    hasError: (state, action) => {
      state.error = action.payload;
      state.isLoading = false;
    },
    loginSuccess: (state, action) => {
      state.user = action.payload;
      localStorage.setItem("user", JSON.stringify(action.payload));
    },
    logoutSuccess: (state, action) => {
      state.user = null;
      localStorage.removeItem("user");
    },
    usersSuccess: (state, action) => {
      state.users = action.payload;
      state.isLoading = true;
    },
    getUsers: (state, action) => {
      state.users = action.payload;
    }
  }
});
export default slice.reducer;
// Actions
const {
  loginSuccess,
  logoutSuccess,
  usersSuccess,
  startLoading,
  hasError
} = slice.actions;

export const fetchUsers = () => async (dispatch) => {
  dispatch(startLoading());
  try {
    await api
      .get("/users")
      .then((response) => dispatch(usersSuccess(response.data)));
  } catch (e) {
    dispatch(hasError(e.message));
  }
};
export const login = ({ username, password }) => async (dispatch) => {
  try {
    // const res = await api.post('/api/auth/login/', { username, password })
    dispatch(loginSuccess({ username }));
  } catch (e) {
    return console.error(e.message);
  }
};
export const logout = () => async (dispatch) => {
  try {
    // const res = await api.post('/api/auth/logout/')
    return dispatch(logoutSuccess());
  } catch (e) {
    return console.error(e.message);
  }
};

export const selectUsers = (state) => state.user.users;
// App.js
const App = (props) => {
  console.log("users", props.users)
  return <div>sample</div>
}
const mapStateToProps = (state) => {
  return { users: selectUsers(state) };
};
export default connect(mapStateToProps)(App);

查看 redux-api-middleware,它提供了一种在 redux 工作流中集成数据获取的更好方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM