繁体   English   中英

Javascript object 键和值

[英]Javascript object keys and values

createSlice 是一个 function,它接受 object 的 reducer 函数,其中 reducer object 中的将用于生成字符串操作类型常量,如下所示:

const counterSlice = createSlice({
  name: 'counter',
  initialState: 0,
  reducers: {
    increment: (state) => state + 1,
  },
})

没关系,但我对此感到困惑。 这个 object 的在哪里?

reducers: {
    increment(state) {
        state.value++
    },
    decrement(state) {
        state.value--
    },
    incrementByAmount(state, action) {
        state.value += action.payload
    }
}

键是incrementdecrementincrementByAmount ,值是函数本身。 这些是“减速器”,它们是作用于您的 state 的函数。

这大致相当于这样说,但语法不同

 reducers: { increment: function(state) { state.value++ }, decrement: function(state) { state.value-- }, incrementByAmount: function(state, action) { state.value += action.payload } }

如果我正确理解你的问题,你是在问reducers object 中的什么被认为是“键”,object 中的“值”是什么。

给定减速器:

reducers: {
  increment(state) {
    state.value++
  },
  decrement(state) {
    state.value--
  },
  incrementByAmount(state, action) {
    state.value += action.payload
  }
}

reducer 键,即incrementdecrementincrementByAmount用于生成字符串操作类型常量和操作创建者。 “值”是返回动作对象的动作创建者函数,即(arg) => ({ type, payload: arg })

基本示例:

const increment = (payload) => ({
  type: 'increment' // <-- reducer key is action type
  payload
});

const decrement = (payload) => ({
  type: 'decrement' // <-- reducer key is action type
  payload
});

const incrementByAmount = (payload) => ({
  type: 'incrementByAmount' // <-- reducer key is action type
  payload
});

createSlice是一个 function,它采用您传递给它的配置 object,它生成缩减器 function 和动作创建器函数。 reducers属性产生的值动作创建者。

也许在不使用 object 属性赋值速记时更容易理解,而是显式地使用函数。

reducers: {
  increment: function increment(state) {
    state.value++
  },
  decrement: function decrement(state) {
    state.value--
  },
  incrementByAmount: function incrementByAmount(state, action) {
    state.value += action.payload
  }
}

或者

reducers: {
  increment: (state) => {
    state.value++
  },
  decrement: (state) => {
    state.value--
  },
  incrementByAmount: (state, action) => {
    state.value += action.payload
  }
}

现在应该更清楚“键”和“值”之间的区别了。

暂无
暂无

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

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