Toolkit 將 reducer, actions 整合至 slice 檔案內,使用 createSlice function 創建
Create Store
configureStore 函式能使用物件導入,當有多支 Reducer ( slice file )需要控管時,可以省略 combineReducer 來作整合,直接以物件形式導入
import { configureStore } from "@reduxjs/toolkit";
import todoReducer from "./slice/todoSlice";
export default configureStore({
reducer: {
// key name should match with initState name.
tasks: todoReducer
},
});
// template
import { configureStore } from '@reduxjs/toolkit';
import reducer from './ reducer file'
export default configureStore(
reducer: { '... reducerStateName: reducer'}
)
CreateSlice
Slice 整合了 reducer, action, action type
import { createSlice } from "@reduxjs/toolkit";
import { nanoid } from "nanoid";
export const todoSlice = createSlice({
name: "tasks",
initialState: [
{ id: nanoid(), task: "Learn Redux", completed: false },
{ id: nanoid(), task: "Learn", completed: false },
],
reducers: {
addTask: (state, action) => {
const newTask = {
id: nanoid(),
task: action.payload.task,
completed: false,
};
state.push(newTask);
},
toggleCompleted: (state, action) => {
const index = state.findIndex((todo) => todo.id === action.payload.id);
state[index].completed = !state[index].completed;
},
deleteTask: (state, action) => {
console.log(action.payload.id);
return state.filter((item) => item.id !== action.payload.id);
},
},
});
export const { addTask, toggleCompleted, deleteTask } = todoSlice.actions;
export default todoSlice.reducer;
// template
import { createSlice } from '@reduxjs/toolkit';
export const 'sliceName' = createSlice({
name: '',
initState: [] // data type, arrary or object
reducers: {
actionName: (state, action) => {
...
}
}
})