在传递给 createStore 的 preloadedState 参数中发现意外的键

Posted

技术标签:

【中文标题】在传递给 createStore 的 preloadedState 参数中发现意外的键【英文标题】:Unexpected key found in preloadedState argument passed to createStore 【发布时间】:2019-09-05 16:21:18 【问题描述】:

我正在尝试编写一个 redux 集成测试。我的测试成功通过,但是,我收到了消息:

console.error node_modules/redux/lib/utils/warning.js:14 “word”。预计会找到一个已知的 reducer 键: “乔托”,“路由器”。意外的键将被忽略。

在我看来,我的 createStore 和 root reducer 看起来不错。有什么我需要改变的东西会破坏这个预加载的状态吗?您可以在下面找到脚本。谢谢!

jotoRedux.test.js:

import createStore, applyMiddleware from 'redux';
import thunkMiddleware from 'redux-thunk';
import routerMiddleware from 'connected-react-router';
import rootReducer from 'reducers/rootReducer';
import initialState from './jottoReducer';
import createBrowserHistory from 'history';

export const history = createBrowserHistory();
const middleware = applyMiddleware(routerMiddleware(history), thunkMiddleware);

export const storeFactory = () =>
  createStore(rootReducer(createBrowserHistory()), ...initialState, middleware);


export const setWord = (word) => (
  type: 'SET_WORD',
  word,
);

describe('testing SET_WORD action', () => 
  let store;
  beforeEach(() => 
    store = storeFactory();
  );

  test('state is updated correctly for an unsuccessful guess', () => 
    store.dispatch(setWord('foo'));
    const expectedState = 
      ...initialState,
      word: 'foo',
    ;
    const newState = store.getState().jotto;
    expect(newState).toEqual(expectedState);
  );
);

jotoReducer.js:

export const initialState = 
  word: null,
;

const jotto = (state = initialState, action) => 
  switch (action.type) 
    case 'SET_WORD':
      return 
        ...state,
        word: action.word,
      ;
    default:
      return state;
  
;

export default jotto;

rootReducer:

import combineReducers from 'redux';
import connectRouter from 'connected-react-router';
import jotto from './jottoReducer';

export default (historyObject) => combineReducers(
  jotto,
  router: connectRouter(historyObject),
);

【问题讨论】:

【参考方案1】:

试试这个:

export const storeFactory = () =>
  createStore(rootReducer(createBrowserHistory()),  jotto: initialState , middleware);

【讨论】:

以上是关于在传递给 createStore 的 preloadedState 参数中发现意外的键的主要内容,如果未能解决你的问题,请参考以下文章

看起来您正在将几个商店增强器传递给 createStore() react-thunk

如何将初始状态传递给减速器

如何将动作传递给 redux 中的组件

redux中createStore方法的默认参数

在 createStore 之前加载数据

redux之createStore方法底层封装模拟