프리랜서 웹디자이너 웹퍼블리셔RELATION

RELATION 로고

DEV

[ react] Redux toolkit

2024.02.25
북마크 작성자 정보
Redux toolkit
- npx create-react-app
- npm install @reduxjs/toolkit

App.js
import { Provider, useSelector, useDispatch } from "react-redux";
import store from "./store/store";
import {up} from "./store/slices_counter";


function Counter(){
  const count = useSelector( (state)=>{ 
    //console.log("state", state);
    return state.counter.value;
  })
  const dispatch = useDispatch();
  return(
    <div>
      
      <button onClick={ () => {
        //dispatch({type:"counterSlice_name/up", step:2});
        //dispatch( counterSlice.actions.up(2))
        dispatch(up(2));
      }}>+</button> 

      {count}
    </div>
  );
}

export default function App() {
  return (
    <Provider store={store}>
      <div>
        <Counter />
      </div>
    </Provider>
  );
}

Store
import { configureStore } from "@reduxjs/toolkit";
import  counterSlice  from "./slices_counter.js";

const store = configureStore({
    reducer : { 
        counter : counterSlice.reducer,
    }
})

export default store;

Slice store
import { createSlice } from "@reduxjs/toolkit";

/*
  createSlide
    name : 슬라이스 이름
    initialState : state 초기값
    reducer : (state, action)
*/

const counterSlice = createSlice({
    name: "counterSlice_name",
    initialState : { value : 0},
    reducers : {
        up : (state, action) => {
            state.value = state.value + action.payload;
        }
    }
});

export default counterSlice;
export const {up} = counterSlice.actions;

 

이 포스트 공유하기

답글쓰기 전체목록