Redux中的异步请求

时间:2017-07-16 19:13:28

标签: javascript reactjs redux redux-thunk

这是我的商店:

import {createStore, applyMiddleware} from 'redux';
import reducerFoo from './reducers/reducer';
import thunkMiddleware from 'redux-thunk';

export default function configureStore() {
  return createStore(
    reducerFoo,
    applyMiddleware(thunkMiddleware)
  );
}

动作:

import * as types from './actionTypes';    
import axios from 'axios';

export const selectTag = function(tag) {

  fetchQuestions(tag);

  return {
    type: types.SELECT_TAG,
    selectedTag: tag
  }
};

export const receiveQuestions = (json) => ({
  type: types.RECEIVE_QUESTIONS,
  questions: json
});

export const fetchQuestions = tag => {

  console.log(tag);

  let url = 'https://api.stackexchange.com/2.2/questions?order=desc&site=stackoverflow ....';    
  console.log(url);

  return function(dispatch) {
    return axios.get(url).then((response) =>
      dispatch(receiveQuestions(response))
    );
  };
};

减速器:

import * as types from '../actions/actionTypes';
import { fetchQuestions } from '../actions/actions';

const initialState = {
  questions: [],
  showTagPanel: true,
  selectedTag: '...',
  tags: ['one', 'two', 'three']
};


export default function reducerFoo(state = initialState, action) {

  switch(action.type) {

    case types.SHOW_TAG_PANEL:

      return Object.assign({}, state, {
        showTagPanel: true
      });

    case types.SELECT_TAG:         

      return Object.assign({}, state, {
        showTagPanel: false,
        selectedTag: action.selectedTag
      });

    case types.RECEIVE_QUESTIONS:

      console.log('get it');
      return state;

    default:
      return state;
  }
}

我可以在控制台中看到urltag

export const fetchQuestions = tag => {

  console.log(tag);

  let url = 'https://api.stackexchange.com/2.2/questions?order=desc&site=stackoverflow ....';    
  console.log(url);

RECEIVE_QUESTIONS操作无效:

case types.RECEIVE_QUESTIONS:
      console.log('get it');
      break;

为什么以及如何解决?

更新:但如果我从index.js调用它,它就可以了:

const store = configureStore();
store.dispatch(fetchQuestions('...'));

更新2:我认为在selectTag()我需要使用

dispatch(fetchQuestions(tag));

而不是

fetchQuestions(tag);

但我不知道如何在这里获得dispatch()

1 个答案:

答案 0 :(得分:1)

fetchQuestions功能中,您有:

return function(dispatch) {
  return axios.get(url).then((response) =>
    dispatch(receiveQuestions(response))
  );
};

但是,您在selectTag函数fetchQuestions(tag);内调用该函数的位置正在返回

function(dispatch) {
  return axios.get(url).then((response) =>
    dispatch(receiveQuestions(response))
  );
};

但它永远不会被其他任何地方召唤。因此,您可以做的一件事是在fetchQuestions内返回该功能,而只需调用axios.get部分,一旦receiveQuestions请求返回,最终将调度get操作。

export const fetchQuestions = tag => {

  console.log(tag);

  let url = 'https://api.stackexchange.com/2.2/questions?order=desc&site=stackoverflow ....';    
  console.log(url);

  return axios.get(url).then((response) =>
    dispatch(receiveQuestions(response))
  );
};