2016-10-14 56 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.終極版:在傳遞給createStore

我發現這個Link,但它並不能幫助我。我不會看到一些東西,也許這部分來自文檔:與傳遞給它的按鍵形狀相同的普通對象

你能否在我的例子中讓我失望?

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謝謝你的表單推薦,但它是sołled的問題 –

+0

你的意思是現在它是否正確地炒作? –

回答

17

TLDR:停止使用combineReducers和你的減速直接傳遞給createStore。使用import reducer from './blabla'而不是import * from './blabla'

createStore(預加載狀態)的第二個參數必須與組合的縮減器具有相同的對象結構。 combineReducers需要一個對象,並將對象中提供的每個reducer應用到相應的state屬性。現在,您正在使用export default導出您的減速器,並將其轉換爲module.exports.default = yourReducer。在導入減速機時,會得到module.exports,相當於{default: yourReducer}。您的預裝狀態沒有default屬性,因此redux抱怨。如果您使用import reducer from './blabla',則會得到module.exports.default,而不是您的減速機。

下面是關於ES6模塊系統如何從MDN工作的更多信息。

閱讀combineReducers來自redux的文檔也可能有幫助。

+0

謝謝你,你是絕對正確的,問題是我的減速器中的字'default' –

+0

謝謝@eugene的解釋 – gca