在分派动作时,Reducer不会捕获

时间:2017-12-15 10:09:49

标签: reactjs api redux

我想在我的小react / redux应用程序中调用api。我还在学习redux,所以显然我并不完美。 我的问题是:当我调用api时,reducer不会从操作中获取数据。 当我登录控制台动作有效负载时,它从服务器获取正确的数据。并且外翻似乎没问题,但是减速器并没有意识到已经发生了动作。这是我的代码:

动作/ apicall.js

import Api from '../api/Api';
import * as types from './actionsTypes';

export function loadSuccess(payload){
console.log(payload)
return {type: types.DATA_LOADED, payload}
};

export function loadData() {
  return function(dispatch) {
    return Api.getAllBeers().then(payload => {
      loadSuccess(payload);
      console.log(payload);
   }).catch(error => {
     throw(error);
   });
  };
}

减速器/ data_reducer

import initialState from './initialState';
import * as types from '../actions/actionsTypes';

export default function beerReducer(state = initialState, action) {
console.log(state);
console.log(action.payload);
  switch(action.type) {
    case types.DATA_LOADED:
      return action.payload
    case types.SELECTED_BEER:
      return action.payload
    default:
     return state;
 }
}

减速器/索引

import { combineReducers} from 'redux';
import beerReducer from './data_reducer';

const allReducers = combineReducers({
    beerReducer,
});

export default (allReducers);

API /原料药

class Api {
  static getAllBeers() {
      const request = new Request(`https://api.punkapi.com/v2/beers`, {
  method: 'GET'
});
    return fetch(request).then(response => {
      return response.json();
    }).catch(error => {
      return error;
    });
  }
}
export default Api;

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './resources/css/main.css';
import App from './resources/App';
import {Provider} from 'react-redux';
import configureStore from './store/configureStore';
import {loadData} from './resources/actions/apicall';

const store = configureStore();

store.dispatch(loadData());

ReactDOM.render(
    <Provider store={store}>
    <App/>
</Provider>, document.getElementById('root'));
你有什么问题吗? 提前谢谢

1 个答案:

答案 0 :(得分:2)

您必须在apicall.js中发送操作: dispatch(loadSuccess(payload));