Redux 中的异步请求

Async request in Redux

这是我的商店:

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=Whosebug ....';    
  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=Whosebug ....';    
  console.log(url);

但是 RECEIVE_QUESTIONS 操作不起作用:

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

为什么以及如何解决?

Update: 但如果我从 index.js:

调用它,它会起作用
const store = configureStore();
store.dispatch(fetchQuestions('...'));

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

dispatch(fetchQuestions(tag));

而不是

fetchQuestions(tag);

但我不知道如何在此处获取 dispatch()

在你的 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 部分,一旦 get 请求 returns.

export const fetchQuestions = tag => {

  console.log(tag);

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

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