【发布时间】:2017-07-16 19:13:27
【问题描述】:
这是我的商店:
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()。
【问题讨论】:
-
你的 reducer 应该是纯的 - 它不应该有副作用。你应该把它移到你的动作创建器中,或者使用中间件/sagas/etc。
-
@OliverCharlesworth,我已移动
fetchQuestion()号召性用语(并编辑问题),但问题仍然存在。 -
Reducer 仍然无效。它应该始终返回一个状态(旧的或新的)。因此,您需要删除
case types.RECEIVE_QUESTIONS:中的break;以恢复默认状态或返回新状态。 -
谢谢。修复它,但仍然不起作用。
-
“更新:但如果我从 index.js 调用它,它会起作用” - @demas 导致您说它起作用的预期行为是什么?
标签: javascript reactjs redux redux-thunk