Redux Toolkit


toolkitの整理


configureStore()


redux devtoolsを使用して自動的に登録します.
const store = configureStore({ reducer });

createAction()


createActionは、長い動作コードを使いやすくします.
console.logが撮れば{type:,payload:}の形式でデータが表示されます.
//action 
const ADD = "ADD";
const DELETE = "DELETE";

const addToDo = text => {
    return {
        type: ADD,
        text
    };
};

const deleteToDo = id => {
    return {
        type: DELETE,
        id: parseInt(id)
    };
};
//--------------------------------------------------------------
//1. redux toolkit createAction을 실행시키면 가 나타난다.
const addToDo = createAction("ADD");
const deleteToDo = createAction("DELETE");

createReducer()

  • 突然変異可能(immer.js内部機能)
  • はまた、新しいオブジェクト
  • を返すことができる.
    //reducer 
    const reducer = (state = [], action) => {
        switch(action.type){
            // case ADD:
            case addToDo.type:
                // return [{text: action.text, id: Date.now()}, ...state];
                return [{text: action.payload, id: Date.now()}, ...state];
            // case DELETE:
            case deleteToDo.type:
                // return state.filter(toDo => toDo.id !== action.id)
                return state.filter(toDo => toDo.id !== action.payload)
            default:
                return state;
        }
    }
    //--------------------------------------------------------------
    
    //2. redux toolkit createReducer을 실행시키면 {type : , payload: }가 나타난다.
    
    const reducer = createReducer([], {
        [addToDo] : (state, action) => {
            //mutate 가능!!!**
            state.push({text: action.payload, id: Date.now()});
        },
        [deleteToDo]: (state, action) => state.filter(toDo => toDo.id !== action.payload)
            
    })

    createSlice()


    createAction+createReducerの機能があり、両方を同時に作成できます.
    const toDos = createSlice({
        name: "toDoReducer",
        initialState: [],
        reducers: {
            add: (state, action) => {
                state.push({text: action.payload, id: Date.now()});
            },
            remove: (state,action) => state.filter(toDo => toDo.id !== action.payload)
        }
    }) 
    
    //toDos.reducer => reducer
    const store = configureStore({ reducer: toDos.reducer });
    
    //toDos.action => action
    export const {add, remove} = toDos.actions;
    
    export default store;

    createSelector()


    createSelector関数は、以前に計算した値をメモリに保存し、値が変更された場合にのみ計算します.
    const shopItemsSelector = state => state.shop.items
    
    const subtotalSelector = createSelector(
      shopItemsSelector,
      items => items.reduce((subtotal, item) => subtotal + item.value, 0)
    )

    createAsyncThunk()


    react-redux


    useDispatch()


    reduxのdispatchを使用できます
    const dispatch = useDispatch();

    useSelector()

    const todos = useSelector(state => state.todos);
    userSelectorを使用してリカバリポイントのステータスをクエリーする場合、ステータスが変更されていない場合は再レンダリングされません.