繁体   English   中英

Redux Reducer可作用于一个节点而不是整个商店

[英]Redux reducer to act on one node rather than whole store

我通常希望我的减速器作用在商店的一个节点上。 它们接收一个节点,并返回该节点的新值。 这就是它的工作方式(并且确实起作用):

shape.reducer.js:

// @flow
import initialState from '../../config/config'

export const shape = (initialShape: string = initialState.get('shape'),
  action: Object): string => {
  switch (action.type) {
    case 'UPDATE_SHAPE': {
      const newShape = action.payload.value
      return newShape
    }
    default:
      return initialShape
  }
}

但是,我现在正在开发其他应用程序,并编写了该应用程序的第一个简化程序。 由于某些原因,它作用于整个商店:

keywords.reducer.js:

// @flow
import initialState from '../../config/config'

const keywords = (initialKeywords: string = initialState.get('searchForm').get('keywords'),
  action: Object): string => {
  switch (action.type) {
    case 'UPDATE_KEYWORDS': {
      const newKeywords = action.payload.value
      return newKeywords
    }
    default:
      return initialKeywords
  }
}

export default keywords

因此,例如,如果关键字更新为“ word”,那么整个商店就变成了“ word”。 两者之间的唯一区别是它们如何传递到createStore

顶级减速机:

const reducer = combineReducers({ height, width, thickness, shape })
const store = createStore(
  reducer,
  initialState,
  composeWithDevTools(applyMiddleware(thunk))
)

底部减速器:

const store = createStore(
  keywords,
  initialState,
  devToolsEnhancer()
)

因此,我尝试对此进行更改,因为这可能会阻止它在整个商店中起作用:

const reducer = combineReducers({ keywords })
const store = createStore(
  reducer,
  initialState,
  devToolsEnhancer()
)

但这导致此错误:

reducer在先前状态下发现意外的属性“ searchForm”。 期望找到一种已知的reducer属性名称代替:“关键字”。 意外的属性将被忽略。

顺便说一句,当应用启动时,这是我的整个商店:

import { Map } from 'immutable'

const searchForm = Map(
  {
    'categories': ['meat'],
    'mealTypes': [],
    'location': {
      place: {},
      distanceFromPlaceValue: 10,
      distanceFromPlaceUnit: 'kilometer'
    },
    'keywords': ''
  }
)

const initialState = Map(
  {
    searchForm: searchForm
  }
)

export default initialState

您已将初始存储设置为一个对象,该searchForm在下面的代码中包含一个名为searchForm的键。

const initialState = Map(
  {
    searchForm: searchForm
  }
)

并且在化简器中,您尝试仅为keywords设置化简器。 理想情况下,您应该为状态中的每个节点使用一个reducer,因此您必须创建4 reducer并按以下方式进行调用

const reducer = combineReducers({ keywords, categories , mealTypes, location })
const store = createStore(
  reducer,
  initialState,
  devToolsEnhancer()
)

最后,您的initialState应该如下所示

const initialState = searchForm;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM