React redux props undefined

问题描述 投票:1回答:1

我是Redux的新手,我很难找到同时使用异步调用和打字稿的良好指南。我试图自己弄清楚它,但是我有点卡住了。如果有人可以看一下我的代码,并可能给我有关如何解决此问题的反馈和/或建议,我将不胜感激!

// types.ts file
export const FETCH_USERS_REQUEST = 'FETCH_USERS_REQUEST';
export const FETCH_USERS_SUCCESS = 'FETCH_USERS_SUCCESS';
export const FETCH_USERS_FAILURE = 'FETCH_USERS_FAILURE';

^我在这里定义常数以保持一致性。

// userActions.ts
import { FETCH_USERS_FAILURE, FETCH_USERS_REQUEST, FETCH_USERS_SUCCESS } from './types';
import { Dispatch } from 'redux';
import axios, { AxiosResponse } from 'axios';

export interface UserProps {
  id: number
  name: string
  email: string
}

export const fetchUsersRequest = () => {
  return {
    type: FETCH_USERS_REQUEST,
  };
};

export const fetchUsersSuccess = (users: Array<UserProps>) => {
  return {
    type: FETCH_USERS_SUCCESS,
    users: users,
  };
};

export const fetchUsersFailure = (error: string) => {
  return {
    type: FETCH_USERS_FAILURE,
    error: error,
  };
};

export const fetchUsers = () => {
  return (dispatch: Dispatch): Promise<unknown> => {
    dispatch(fetchUsersRequest());
    return axios.get('https://jsonplaceholder.typicode.com/users')
      .then((response: AxiosResponse<UserProps[]>) => {
        dispatch(fetchUsersSuccess(response.data));
        return response.data;
      })
      .catch((error: string) => {
        dispatch(fetchUsersFailure(error));
      });
  };
};

userReducer

import { UserProps } from '../actions/userActions';
import { FETCH_USERS_FAILURE, FETCH_USERS_REQUEST, FETCH_USERS_SUCCESS } from '../actions/types';

interface Action {
  type: string
  payload: Array<UserProps> | string,
}

export interface initialStateProps {
  loading: boolean,
  users: Array<UserProps>
  error: string
}

const initialState: initialStateProps = {
  loading: false,
  users: [],
  error: '',
};

export const userReducer = (state = initialState, action: Action) => {
  switch (action.type) {
    case FETCH_USERS_REQUEST:
      return {
        ...state,
        loading: true,
      };
    case FETCH_USERS_SUCCESS:
      return {
        loading: false,
        users: action.payload,
      };
    case FETCH_USERS_FAILURE:
      return {
        loading: false,
        users: [],
        error: action.payload,
      };
    default: {
      return state;
    }
  }
};

export const getUsers = (state: initialStateProps) => state.users;
export const getUsersRequest = (state: initialStateProps) => state.loading;
export const getUsersFailure = (state: initialStateProps) => state.error;

然后在我的项目中,我使用connected-router帮助跟踪路线。

import { combineReducers } from 'redux';
import { History } from 'history';
import { connectRouter } from 'connected-react-router';
import { userReducer } from './userReducers';

export const createRootReducer = (history: History) => combineReducers({
  router: connectRouter(history),
  userReducer,
});

商店:

import { createBrowserHistory } from 'history';
import { applyMiddleware, compose, createStore } from 'redux';
import thunkMiddleware from 'redux-thunk'
import { createLogger } from 'redux-logger';
import { routerMiddleware } from 'connected-react-router';
import { createRootReducer } from './reducers';

export const history = createBrowserHistory();

const loggerMiddleware = createLogger();

export const configureStore = (preloadedState?: any) => {
  const composeEnhancer: typeof compose = (window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
  return createStore(
    createRootReducer(history),
    preloadedState,
    composeEnhancer(
      applyMiddleware(
        routerMiddleware(history),
        thunkMiddleware,
        loggerMiddleware,
      ),
    ),
  );
};

并且在应用程序中,我使用此:

const mapStateToProps = (state: initialStateProps) => ({
  error: getUsersFailure(state),
  users: getUsers(state),
  loading: getUsersRequest(state)
});

const mapDispatchToProps = (dispatch: Dispatch) => bindActionCreators({
  fetchUsers: fetchUsers
}, dispatch);

export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(TopbarNav);

但是当我console.log(props);我得到:

users: undefined

loading: undefined

error: undefined

编辑:在这里,我运行fetchUsers:

const TopbarNav: React.FC = (props: any) => {

  const [loading, setLoading] = React.useState(true);

  const classes = useStyles();

  useEffect(() => {
    props.fetchUsers();
  });

  const handler = () => {
    console.log({props});
  };
};

我在这个问题上省略了render方法。

编辑2更新了useEffect方法:

const [users, setUsers] = React.useState([]);

const [loading, setLoading] = React.useState(true);

const classes = useStyles();

useEffect(() => {
  setUsers(props.fetchUsers());
}, [users, props, loading]);

const handler = () => {
  console.log(props.loading);
};
reactjs redux react-redux redux-thunk react-props
1个回答
0
投票

通过以这种方式使用combineReducers,我认为您的状态将看起来像这样

{
  router: ...,
  userReducer: ...,
}

因此您可以通过修改选择器以查找正确的道具来进行修复

state.userReducer.users
state.userReducer.loading
...
© www.soinside.com 2019 - 2024. All rights reserved.