下载
yarn add @reduxjs/toolkit react-redux
创建两个js文件一个是store和一个toolkit 碎片
todoSlice
import { createSlice } from '@reduxjs/toolkit'
//必须有一哥初始值
const initialState = {
todo: [
{ id: 0, name: "吃饭", done: true },
{ id: 1, name: "睡觉", done: false },
{ id: 2, name: "打豆豆", done: false }
]
}
export const todoSlice = createSlice({
name: 'todoSlice',
initialState,
reducers: {
increment: (state = initialState, action) => {
// Redux Toolkit允许我们在reducers中直接写改变state的逻辑.
// 由于使用了Immer库,所以并没有真的改变state
state.todo.push(action.payload)
},
decrement: (state, action) => {
state.todo.splice(action.payload, 1)
},
changedone: (state, action) => {
state.todo[action.payload.index].done = action.payload.done
},
cleardone: (state, action) => {
state.todo=state.todo.filter(item=>{
return item.done!==true
})
}
},
})
// reducer方法的每一个case都会生成一个Action
export const { increment, decrement, changedone, cleardone } = todoSlice.actions
export default todoSlice.reducer
store
import { configureStore } from '@reduxjs/toolkit'
import todoSlice from "./todoSlice.js"
export const store = configureStore({
reducer: {
todos: todoSlice,
}
})
在index.js对store进行处理