50

Redux レデューサーの結合を開始する前に、私のアプリは正常に動作します。しかし、組み合わせると、initialState キーと reducer キーが混同されます。

function flash(state = [], action) {
  switch (action.type) {
  case FLASH_MESSAGE_UPDATED:
    return _.extend({}, state, { flash: action.flash })
  default:
    return state
  }
}

function events(state = [], action) {
  switch (action.type) {
  case EVENTS_UPDATED:
    return _.extend({}, state, { events: action.pathway_events })
  default:
    return state
  }
}

export default combineReducers({
  events,
  flash
})

これにより、機能が壊れ、次のコンソール エラーが発生します。

Unexpected keys "one", "two" found in initialState argument passed to createStore. Expected to find one of the known reducer keys instead: "events", "flash". Unexpected keys will be ignored.

私の初期状態は redux-thunk の助けを借りて渡されます。

import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import reducer from '../../reducers/event'

let initialState = {
  one: globalData.one,
  two: globalData.two,
  events: globalData.events,
  flash: globalData.flash
}
let createStoreWithMiddleware = applyMiddleware(thunk)(createStore)
let reduxStore = createStoreWithMiddleware(reducer, initialState);

React.render(
  <Provider store={reduxStore}>
    <EventListContainer />
  </Provider>,
  $('.events')[0]
)

レデューサーを正しく組み合わせるにはどうすればよいですか?

4

2 に答える 2

64

追加のキーのレデューサーを追加するだけでよいと思います。

function one(state = {}, action) {
  switch (action.type) {
  case ONE_UPDATED:
    return action.one
  default:
    return state
  }
}

ドキュメントから:

CombineReducers を使用してレデューサーを作成した場合、これは、渡されたキーと同じ形状のプレーン オブジェクトである必要があります。それ以外の場合は、レデューサーが理解できるものを自由に渡すことができます。

oneまたはに関連するアクションを処理する必要がない場合はtwo、最初にそれらをプルするだけです。これは次のように簡単です。

export default combineReducers({
  events,
  flash,
  one: (state = {}) => state,
  two: (state = {}) => state
})
于 2015-11-12T18:00:25.590 に答える