북마크 작성자 정보
작성일/수정일
2024-02-25 15:13:59 / 2024-02-25 15:13:59
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;