redux Javascript对象键和值

1bqhqjot  于 2023-01-13  发布在  Java
关注(0)|答案(2)|浏览(108)

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

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

这是可以的,但我对此感到困惑。这个对象的在哪里?

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

jdg4fx2g1#

如果我没理解错的话,你是在问reducers对象中的什么被认为是“键”,什么是该对象中的“值”。
给定减速器:

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

reducer键incrementdecrementincrementByAmount用于生成字符串action类型常量和action创建者,“values”是返回action对象的action创建者函数(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是一个函数,它接受您传递给它的配置对象,并生成reducer函数和action creator函数。reducers属性***生成的值是***action creators。
如果不使用对象属性赋值简写,而是显式地使用函数,可能会更容易理解。

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

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

dly7yett

dly7yett2#

键是incrementdecrementincrementByAmount,值是函数本身。这些是“reducer”,是作用于你的状态的函数。
它大致等同于这样说,但语法不同

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

相关问题