如果条件与Redux匹配,我如何增加值?

niwlg2el  于 2022-11-12  发布在  其他
关注(0)|答案(1)|浏览(127)

我是redux的新手。我想在条件匹配的情况下将状态加一。条件为真,我在控制台上检查过了。这是action;

if(btn.target.value == answer) {
            dispatch(calculate(prev => prev +1))
}

这是国家;

export const scoreSlice = createSlice({
name: "score",
initialState: {value: 0}, 
reducers: {
    calculate: (state,action) => {
        state.value = action.payload
    }
}

控制台输出;

prev => prev + 1
vngu2lb8

vngu2lb81#

调度操作时,请传递要添加到值中的数字

if (btn.target.value == answer) {
  dispatch(calculate(1))
}

在reducer function中=〉action.payload表示在调度函数时传递给它的任何内容(这里action.payload = 1)

const reducers = {
  calculate: (state, action) => ({
    ...state, // copy original state
    value: state.value + action.payload
  })
}

相关问题