이제 store로 이동.
기본 형태는 이러하다.
import { configureStore } from '@reduxjs/toolkit';
import budgetReducer from './slices/budgetSlice';
const store = configureStore({
reducer: {
buget: budgetReducer,
},
});
export default store;
configurestore을 가져오고, slice 파일을 가져온다.
여기서의 리듀서는 리덕스 스토어에 어떤 리듀서를 사용할지 알려준다.
그리고 main.jsx에 가서
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>
);
이렇게 감싸준다.
import { createSlice } from '@reduxjs/toolkit';
const initialState = {
// 처음에 어떤 상태로 시작할 것이냐 (초기 상태)
saveMonth: Number(localStorage.getItem('month')) || 5,
itemListt: [],
};
export const budgetSlice = createSlice({
name: 'budget',
initialState,
reducers: {
setSaveMonth: (state, action) => {
state.saveMonth = action.payload;
localStorage.setItem('month', action.payload);
},
},
});
export const { setSaveMonth } = budgetSlice.actions;
export default budgetSlice.reducer;
이제 뭐 이런식으로 하면 되겠지 ㅎ 했는데 아니었다.
useSelector라는 놈을 사용해야 한다.
그러니까 우리는 스토어를 가지게 되었는데, 여기서 number라는 값을 컴포넌트에서 사용하고 싶다면
const number = useSelector(state => state.counter.number); // 0
이런 식으로 써줘야 한다.
1. useSelector를 변수에 할당
2. 인자에 화살표 함수를 넣어줌
3. 함수의 인자에서 값을 꺼내 리턴
한 것이다.
'리액트' 카테고리의 다른 글
리액트 쿼리 사용하기 (0) | 2024.06.14 |
---|---|
24. 06. 07 TIL redux-4 (0) | 2024.06.07 |
24. 06. 04 TIL redux-2 (0) | 2024.06.04 |
24. 06. 03 TIL redux-1 (0) | 2024.06.03 |
24. 05. 31 TIL (context api) (0) | 2024.05.31 |