首页 > 解决方案 > 在 Redux 中,reducer 无法识别动作对象

问题描述

我将 Redux 用于 React 项目。出于某种原因,我的 reducer 无法识别type发送给它的操作,甚至无法识别操作本身。我得到这个错误TypeError: Cannot read property 'type' of undefined。而且我知道我正在使用dispatch.

来自服务器的 api 工作正常,我已经通过 Postman 进行了测试。

但我不明白 redux 发生了什么。

请问,有人可以给我建议吗?

在取消我的问题之前,我已经阅读了许多看起来相似但没有回答我的问题的 SO 帖子,因此我在这里问它。

谢谢。

行动:

import axios from 'axios';

export const GET_ALL_USERS = 'GET_ALL_USERS';

export const showAllUsers = () => dispatch => {
  console.log('USERS ACTION');

  return axios
    .get('/api/users/all')
    .then(res => {
      console.log('GETTING ALL USERS ACTION', res);

      return dispatch({
        type: GET_ALL_USERS,
        payload: res.data
      });
    })
    .catch(err => console.log('Oops! Cannot get any users.'));
};

减速器:

import { GET_ALL_USERS } from '../actions/usersActions';

const InitialState = {
  users: null,
  loading: false
};

export default function(state = InitialState, action) {
  console.log('USERS REDUCER', action);

  switch (action.type) {
    case GET_ALL_USERS:
      return {
        ...state,
        users: action.payload
      };
    default:
     return state;
  }
}

反应:

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import './index.css';
import App from './containers/App';
import registerServiceWorker from './registerServiceWorker';

import rootReducer from './reducers';

let middleware = [thunk];

const store = createStore(
  rootReducer,
  {},
  compose(
    applyMiddleware(...middleware),
    window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
  )
);

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
);
registerServiceWorker();

反应组件:

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';

import { showAllUsers } from '../../actions/usersActions';

export class Admin extends Component {
  constructor(props) {
    super(props);

    this.state = {};
  }

  componentDidMount() {
    this.props.showAllUsers();
  }

  render() {
    const { users } = this.props;
    console.log(`All users in admin`, this.props.users);

    return (
      <div className="admin">
        <h1 className="admin__title">Admin Board</h1>
        {this.props.users.map(user => {
          return (
            <article>
              <img src={user.avatar} alt={user.username} />
              <p>{user.firstName}</p>
              <p>{user.lastName}</p>
              <p>{user.username}</p>
              <p>{user.email}</p>
            </article>
          );
        })}
      </div>
    );
  }
}

const mapStateToProps = state => ({
  users: state.users
});

export default connect(mapStateToProps, { showAllUsers })(Admin);

标签: javascriptreactjsreduxreact-redux

解决方案


showAllUsersasync action。你需要一些中间件来dispatch async action.

使用redux-thunkorredux-saga并将其与 store 集成。这将有助于执行asynchronous dispatch

import thunkMiddleware from 'redux-thunk';
let middleWares = [thunkMiddleware];


const store = createStore(
  rootReducer, applyMiddleware(...middleWares)
)

如果你dispatch async采取行动synchronous,错误TypeError: Cannot read property type of undefined将被抛出。


推荐阅读