这是我的商店:
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;
}
}
我可以在控制台中看到url
和tag
:
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()
。
答案 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))
);
};