如何在react redux中使用.dispatch?

9rygscc1  于 11个月前  发布在  React
关注(0)|答案(1)|浏览(97)

我有以下

CatsPage.js:

import React from 'react';
import PropTypes from 'prop-types';
import {connect} from 'react-redux';
//import * as catActions from '../../actions/catActions';
import CatList from './CatList';
import {loadCats} from '../../actions/catActions';

class CatsPage extends React.Component {
  componentDidMount () {
    this.props.dispatch(loadCats())
  }
  render() {
    return (
      <div>
        <h1>Cats</h1>
        <div>
          <CatList cats={this.props.cats} />
        </div>
      </div>
    );
  }
}

CatsPage.propTypes = {
  cats: PropTypes.array.isRequired
};

function mapStateToProps(state, ownProps) {
  return {
    cats: state.cats
  };
}

export default connect(mapStateToProps)(CatsPage);

字符串
catActions.js**

import * as types from './actionTypes';
import catApi from '../api/CatsApi';

export function loadCats() {
  return function(dispatch) {
    return catApi.getAllCats().then(cats => {
      dispatch(loadCatsSuccess(cats));
    }).catch(error => {
      throw(error);
    });
  };
}

export function loadCatsSuccess(cats) {
  return {type: types.LOAD_CATS_SUCCESS, cats};
}


我得到以下错误:
第一个月
我是一个初学者,正在学习如何使用React + Redux。我做错了什么,我需要修复以使分派工作和loadCats()?

k3bvogb1

k3bvogb11#

您可能没有正确安装/配置您的商店。它应该看起来像这样:

import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers/index';

// Note: this API requires redux@>=3.1.0
const store = createStore(
  rootReducer,
  applyMiddleware(thunk)
);

字符串

相关问题