React-Redux - 如何在应用程序状态中设置字段?

时间:2016-07-29 17:34:22

标签: javascript reactjs redux react-redux

我正在使用React和Redux学习Fractal Structure,但是当我想要设置应用程序状态时,我发现它被阻止了。

我会尝试解释我的问题

的src /路由器/计数器/ index.js

import { injectReducer } from '../../store/reducers'

export default (store) => ({
  path: 'counter',
  getComponent (nextState, cb) {
    require.ensure([], (require) => {
      const Counter = require('./containers/CounterContainer').default
      const reducer = require('./modules/counter').default

      /*  Add the reducer to the store on key 'counter'  */
      injectReducer(store, { key: 'counter', reducer })

      cb(null, Counter)

    }, 'counter')
  }
})

的src /路由器/计数器/模块/ counter.js

// ------------------------------------
// Constants
// ------------------------------------
export const COUNTER_INCREMENT = 'COUNTER_INCREMENT'

// ------------------------------------
// Actions
// ------------------------------------
export function increment (value = 1) {
  return {
    type: COUNTER_INCREMENT,
    payload: value
  }
}

export const actions = {
  increment
}

// ------------------------------------
// Action Handlers
// ------------------------------------
const ACTION_HANDLERS = {
  [COUNTER_INCREMENT]: (state, action) => state + action.payload
}

// ------------------------------------
// Reducer
// ------------------------------------
const initialState = 0
export default function counterReducer (state = initialState, action) {
  const handler = ACTION_HANDLERS[action.type]

  return handler ? handler(state, action) : state
}

的src /路由/计数器/容器/ CounterContainer.js

import { connect } from 'react-redux'
import { increment } from '../modules/counter'

import Counter from 'components/Counter'

const mapActionCreators = {
  increment: () => increment(1)
}

const mapStateToProps = (state) => ({
  counter: state.counter
})

export default connect(mapStateToProps, mapActionCreators)(Counter)

我希望在计数器状态下设置更多字段,因为我可以通过分隔传递道具。即:

const mapStateToProps = (state) => ({
      max: state.counter.max
      min: state.counter.min
})

那么,如何在state.counter中设置字段?

谢谢。

1 个答案:

答案 0 :(得分:1)

您需要使用reducer来更新sate属性。你的柜台就是这样的东西。

function counter(state = initialState, payload) {
  switch (action.type) {
    case UPDATE_COUNTER:
      return Object.assign({}, state, {
        counter: {max:payload.max,min:payload.min}
      })
    default:
      return state
  }
}