-
[React] 리덕스 초기 세팅, 리듀서만들기 복습Java Script & Type Script 2023. 3. 21. 01:00728x90
리덕스에대해 이해가 부족한 것 같아서 반성하면서 이용법을 천천히 다시 공부하고있다...
import { configureStore } from "@reduxjs/toolkit"; export default configureStore({ reducer: {}, });
import { Provider } from "react-redux"; import store from "./store.js"; const root = ReactDOM.createRoot(document.getElementById('root')); root.render( <React.StrictMode> <Provider store={store}> <BrowserRouter> <App /> </BrowserRouter> </Provider> </React.StrictMode> );
이제 <App>과 그 모든 자식컴포넌트들은 store.js에 있던 state를 맘대로 꺼내쓸 수 있습니다!
store.js에서,
const user = createSlice({ name: "user", initialState: "Kim", }); //1단계, { name : 'state이름', initialState : 'state값' } 형태로 state를 하나 만든다. export default configureStore({ reducer: { user: user.reducer, }, //2단계, configureStore에 등록한다. 그럼 모든 컴포넌트에서 자유롭게 사용할 수 있다. });
이제 쓰고자하는 컴포넌트에서
const state = useSelector((state)=>return state)
이렇게 변수에 넣어주면 redux store에 있던 state가 남는다 .
const state = useSelector((state) => { return state.user; });
이렇게하면 state전체에서 user로 저장한 내용만 저장되고!
const user = createSlice({ name: "user", initialState: "Kim", reducers: { changeName(state) { return "john" + state; }, }, }); export const { changeName } = user.actions;
리덕스의 state를 변경하는 함수를 넣으면 이런 모양.
리듀서 만들 때, state가 object이면
{ name: "Kim", age: 20 },
changeAge(state) { state.age += 1; },
이런 return 없는 형태도 허용된다. object자료 수정문법.
리듀서에 파라미터 추가하기.
reducers: { changeName() { return { name: "John", age: 20 }; }, changeAge(state, action) { state.age += action.payload; },
두번째파라미터.payload
이제 changeAge(10)이런 식으로 쓸 수 있음
참고
- action.type 하면 state변경함수 이름이 나오고
- action.payload 하면 파라미터가 나옵니다.
addCount(state, action) { const number = state.findIndex((a) => { return a.id === action.payload; }); state[number].count++; },
많이 쓰는 형태
728x90'Java Script & Type Script' 카테고리의 다른 글
[Refactor] Gnims 코드 리팩토링 with Chat GPT (0) 2023.03.22 [React] 다섯종류의 조건부 렌더링 (0) 2023.03.21 43. Ajax- Axios, Promise.all, fetch함수 복습하기 (0) 2023.03.18 [React] 컴포넌트의 Lifecycle [useEffect에대한 고찰 2] 컴포넌트야 인생 원래 그런거야 (0) 2023.03.18 [React] Styled component props 문법 (0) 2023.03.17