老师,关于新版redux的reducer返回值问题
来源:12-10 使用Redux实现数字加减法-使用useSelector和useDispatch
菜到眼泪流下来
2023-10-07
看到同学的提问,也看了一下redux关于reducer修改state的示例代码,报错了
state
import {createSlice} from '@reduxjs/toolkit'
export const countSlice = createSlice({
name:'count',
initialState:100,
reducers:{
add:state =>{ state+=1}, // 示例代码没有返回值,但是报错了
sub:state => state-=1 // 有返回值的没有报错
}
})
export const {add,sub} = countSlice.actions
export default countSlice.reducer示例代码
import { createSlice } from '@reduxjs/toolkit'
export const counterSlice = createSlice({
name: 'counter',
initialState: {
value: 0
},
reducers: {
increment: state => {
// Redux Toolkit 允许我们在 reducers 写 "可变" 逻辑。它
// 并不是真正的改变状态值,因为它使用了 Immer 库
// 可以检测到“草稿状态“ 的变化并且基于这些变化生产全新的
// 不可变的状态
state.value += 1
},
decrement: state => {
state.value -= 1
},
incrementByAmount: (state, action) => {
state.value += action.payload
}
}
})
// 每个 case reducer 函数会生成对应的 Action creators
export const { increment, decrement, incrementByAmount } = counterSlice.actions
export default counterSlice.reducer这是为什么?
写回答
1回答
-
双越
2023-10-08
最新的 redux 已经集成了 immer 库,所以它可以直接修改属性。按照这个示例来写即可,不用再自己引入 Immer 了
052023-10-08
相似问题