#리덕스는 애플리케이션의 상태를 관리하기 위한 오픈소스 자바스크립트 라이브러리이다
리덕스를 쓰는 이유는 흔히 데이터를 전달할때 props로 할수도 있지만 너무 많은 페이지가 있다면 정말 복잡해진다
그걸 줄이고 편하게 이용하기 위해 리덕스를 쓴다.
#리덕스 코어설치
npm install redux
npm install @reduxjs/toolkit
npm i sass react-redux @reduxjs/toolkit
-타입스크립트에서는 @types/react-redux를 추가로 설치
1.store - 단하나만 생성 가능하면 생성하여 상태를 관리 할 수 있음
import { configureStore, createSlice } from "@reduxjs/toolkit";
const resultInput = createSlice({ //1.리덕스 함수 생성하기 - reducer 함수와 action creator 를 포함한 객체
name: "resultInput", //name : 해당 모듈의 이름을 작성
initialState: false, //초기값 지정
reducers: { //2.리듀서
//rInput:(state) => !state,
rInput: (state, action) => { //원하는 동직 지정하기 #주의: 순수 함수여야함 / 해당 리듀서의 키값으로 액션함수가 자동으로 생성
//console.log(state);
switch (action.payload) {
case "search":
state = true;
return state;
default:
state = false;
//여기서 이부분을 안쓰면 디폴트라 해서 초기값이 지정되는것이 절대아님★
//이전에 저장된값이 디폴트로 박힘! 데이터를 저장하는곳이기 때문에!! 혼동금지
return state;
}
}
}
})
export const { rInput } = resultInput.actions; //2.리듀서를 export해야 사용가능
export const redux_store = configureStore({ //Reducer에서 반환된 새로운 state를 Store라는 객체로 정리해 관리하는곳
reducer: {
resultInput: resultInput.reducer,
},
});
export default redux_store;
1)createSlice으로 state의 초기값들과 action creator와 reducer를 생성해준다.
2)모든 slice들을 combineReducers으로 결합시켜서 하나로 모아준다.
3)위에서 combineReducers으로 모아준 reducer를 최종적으로 configureStore에서 반환후 사용한다.
도움받은곳:https://heokknkn.tistory.com/32
2.연결하기 - 최상위 index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom';
import { Provider } from "react-redux"; //1.전역으로 사용하기 위해 import
import App from './App';
import redux_store from "./redux_store"; //리덕스파일 import
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<BrowserRouter basename={process.env.PUBLIC_URL}>
<Provider store={redux_store}> {/*2.연결하기 */ }
<App />
</Provider>
</BrowserRouter>
</React.StrictMode>
);
store를 리액트 컴포넌트에서 사용하기 위해 연동을 시켜줘야 한다.
리액트에 Store를 연동 할 때는 react-redux 라이브러리 안에 들어있는 Provider라는 컴포넌트를 사용한다.
기존의 TSX를 Provider로 감싸고, store는 Props로 Provider한테 넣어준다.
3.사용하기
import { useDispatch, useSelector } from "react-redux"; // 사용하기
/*
useDispatch : Dispatch를 통한 상태 업데이트 - hooks 문법으로 useDispatch라는 모듈을 사용
useSelector : 현재 상태값 가져오기
-쉽게 생각하면 useState에서 [useSelector,useDispatch] 이렇게 생각하면 쉬움
*/
import { rInput } from "./redux_store"; // 사용할 부분
/* redux_store에서 export한
export const { rInput } = resultInput.actions; //2.리듀서를 export해야 사용가능
이부분과 맞춰준다!
*/
const Search = () => {
const [input, setInput] = useState("");
const { resultInput } = useSelector((s) => s); //리덕스 함수를 가져와서 상태값 쓰기
const dispatch = useDispatch();
//상태를 업데이트 할때는 생성한 dispatch함수를 사용해 dispatch(action)의 형태로 상태를 업데이트 할 수 있다.
//Dispatch의 전달인자로 Action 객체가 전달된다
useEffect(() => { //사용해보기 - 예시임
if (resultInput) {
} else {
setInput("");
}
//console.log(resultInput);
},[resultInput])
return (
<div className="Search">
///소스들~
</div>
)
}
export default Search;
++search페이지를 분리하기 위해
1)결과페이지
useEffect(() => {
dispatch(rInput("search")); //true
}, [query, page]);
2)메인페이지
useEffect(() => {
dispatch(rInput("main")); //false - 이부분을 안쓰면 써치에서 바꼈기 때문에 false가 찍힘
//데이터가 저장되어있다는것을 까먹으면 안됌..데이터를 왔다리 갓다리 하기때문에
//간편하게 쓸때는 createContext 더좋을수도있음
},[])
도움받은곳:
https://chanyeong.com/blog/post/21
https://velog.io/@jjburi/Redux
https://velog.io/@starrypro/React-%EC%83%81%ED%83%9C%EA%B4%80%EB%A6%AC-Redux
기본저서:
https://react-redux.js.org/tutorials/quick-start#install-redux-toolkit-and-react-redux
Quick Start | React Redux
react-redux.js.org
'React' 카테고리의 다른 글
useEffect (0) | 2023.04.25 |
---|---|
Context (0) | 2023.02.17 |
Vercel로 배포하기 (0) | 2023.01.12 |
Next.js styled-component (0) | 2023.01.10 |
Next.js (0) | 2023.01.10 |