Redux似乎让州/减少者混淆

时间:2018-03-07 00:53:57

标签: reactjs redux react-redux

我有一个非常奇怪的问题,我的减速器似乎正在修改他们不应该修改的部分状态,我确信这是由于我的实施中的一些疏忽,但我不能追踪它。

我目前有一个商店,两个动作/动作创建者,两个减速器和一个减速器。这是我的代码,(遗漏了一些不重要的细节):

//actionTypes.ts

export const SUBMIT_SEARCH = "SUBMIT_SEARCH";
export const CHANGE_SEARCH_PAGE = "CHANGE_SEARCH_PAGE";

-

//actionCreators.ts

import { SUBMIT_SEARCH, CHANGE_SEARCH_PAGE } from "./actionTypes"

export const submitSearch = (submitSearch) => ({
    type: SUBMIT_SEARCH,
    submitSearch
});

export const changeSearchPage = (changeSearchPage) => ({
    type: CHANGE_SEARCH_PAGE,
    changeSearchPage
});

-

//submitSearchReducer.ts

import { SUBMIT_SEARCH } from "../actions/actionTypes";

const submitSearch = (state = {}, action) => {
    switch (action.type) {
    case SUBMIT_SEARCH:
        return {
            ...state,
            submitSearch: action.submitSearch
        }
    default:
        return state;
    };
};

export default submitSearch;

-

//changeSearchPageReducer.ts

import { CHANGE_SEARCH_PAGE } from "../actions/actionTypes";

const changeSearchPage = (state = {}, action) => {
    switch (action.type) {
        case CHANGE_SEARCH_PAGE:
            return {
                ...state,
                changeSearchPage: action.changeSearchPage
            }
        default:
            return state;
    };
};

export default changeSearchPage;

-

//rootReducer.ts

import { combineReducers } from 'redux';
import submitSearch from "../reducers/submitSearchReducer"
import changeSearchPage from "../reducers/submitSearchReducer";

const rootReducer = combineReducers({
    submitSearch: submitSearch,
    changeSearchPage: changeSearchPage
});

export default rootReducer;

-

我像这样创建商店:

const logger = createLogger();
const store: Store<any> = createStore(rootReducer, {/*Initial state empty*/}, applyMiddleware(logger));

-

总体流程如下:

  • 用户在触发store.dispatch(submitSearch(string))来电
  • 的页面上输入搜索字符串
  • 用户在页面上输入一个号码,触发store.dispatch(changeSearchPage(newPage))

这是我记录器的输出:

[![搜索电话] [1]] [1] [![更改页面调用] [2]] [2]

你可以在这里看到状态显然已经混淆了,错误的数据将转到changeSearchPage键。

造成这种混乱的原因是什么?

1 个答案:

答案 0 :(得分:1)

在rootReducer中,您将导入相同的reducer两次