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

React-Redux - How to set fields inside state of application?

本文关键字:程序状态 设置 字段 应用 Redux- React      更新时间:2023-09-26

我正在用React和Redux学习分形结构,但当我想设置应用程序状态时,我发现它被阻止了。

我会尽力解释我的问题

src/router/Counter/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/router/Counter/modules/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/routes/Counter/containers/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中设置字段呢?

谢谢。

您需要使用reducer来更新状态属性。像这样的东西给你的柜台。

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
  }
}