2016-10-14 1 views
7

に渡されたpreloadedState引数で見つかった予期しないキーを使用して、例外Unexpected key "userName" found in preloadedState argument passed to createStore. Expected to find one of the known reducer keys instead: "default". Unexpected keys will be ignored.Reduxの:CREATESTORE

で私を助けることができる私はこのLinkを発見したが、それは私を助けていません。私はundestand何か、おそらくドキュメントからこの部分:渡されるキーと同じ形のプレーンオブジェクト

私の例で私の間違いをexlainできますか?

import React from "react"; 
import ReactDOM from "react-dom"; 
import { Provider } from 'react-redux'; 
import { createStore, combineReducers, applyMiddleware } from 'redux'; 
import App from './containers/App.jsx'; 
import * as reducers from './reducers' 
import types from './constants/actions'; 

const reducer = combineReducers(reducers); 

const destination = document.querySelector("#container"); 

var store = createStore(reducer, { 
    userName : '' 
}); 


ReactDOM.render(
    <Provider store={store}> 
     <App/> 
    </Provider>, 
    destination 
); 

console.log(1) 

store.subscribe(()=> { 
console.log("-------------------------") 
let s = store.getState() 
console.log("STATE = " + s) 
for (var k in s) { 
    if (s.hasOwnProperty(k)) { 
     console.log("k = " + k + "; value = " + s[k]); 
    } 
} 
}) 

store.dispatch({ 
     type: types.LOAD_USER_NAME, 
     userName : "Oppps1" 
}) 

私の減速:実行後のコンソールで

import types from './../constants/actions' 

export default function userNameReducer (state = {userName : 'N/A'}, action) { 
console.log('inside reducer'); 
switch (action.type) { 
    case types.LOAD_USER_NAME: 
     console.log("!!!!!!!!!!!!!!!") 
     console.log("action.userName = " + action.userName) 
     for (var k in state) { 
      if (state.hasOwnProperty(k)) { 
       console.log("k = " + k + "; value = " + state[k]); 
      } 
     } 
     return action.userName; 
    default: 
     return state 
} 
} 

結果:

enter image description here

+0

あなたのレデューサーは純粋な機能でなければならないので、副作用(console.logのもの)を取り除いてください。 –

+0

@IslamIbakaevさんはフォームのご提案に感謝しますが、問題をかき消してしまいました –

+0

今、 –

答えて

17

TLDR:combineReducersの使用を停止し、直接createStoreにあなたの減速を渡します。 import * from './blabla'の代わりにimport reducer from './blabla'を使用してください。

createStore(プリロードされた状態)の2番目の引数は、結合されたレデューサーと同じオブジェクト構造でなければなりません。 combineReducersはオブジェクトを取得し、オブジェクト内で提供されている各レデューサーを対応する状態プロパティに適用します。今度はexport defaultを使って還元剤を輸出しています。これはmodule.exports.default = yourReducerのようなものに転化されています。あなたは減速機をインポートすると、あなたは{default: yourReducer}に等しいmodule.exportsを得ます。プリロードされた状態にdefaultのプロパティがないため、不満を訴えます。 import reducer from './blabla'を使用した場合は、還元剤と同等のmodule.exports.defaultが得られます。

MDNからES6モジュールシステムがどのように機能するかについて詳しくはこちら。

combineReducersからのレフィックスの閲覧はお役に立ちます。

+0

ありがとうございます、あなたは絶対に正しいです、問題は私の減速の単語 'デフォルト'だった –

+0

ありがとう@eugene説明 – gca