在Redux中,reducer无法识别操作对象

时间:2018-06-14 14:06:39

标签: javascript reactjs redux react-redux

我正在使用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);

1 个答案:

答案 0 :(得分:6)

showAllUsersasync action。您需要一些中间件到dispatch async action

使用redux-thunkredux-saga并将其与商店集成。 它将有助于执行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