yarn add redux
yarn add react-redux
한번에 설치 하려면 중간에 띄어쓰기하면 됨
yarn add redux react-redux
createStore불러오기
import {createStore} from 'redux'
store 생성
const store = createStore();
createStore는 필수 인자로 reducer를 받음
reducer는 현재 state와 action값을 인자로 받아 작업하고 새로운 state를 return 함
createStore의 필수인자로 reducer전달
function reducer(state, action){
return
}
const store = createStore(reducer);
reducer를 처음 호출 할때 state 값은 undefined로 값이 없기때문에 대응로직 생성
state 값을 부수효과로 변경하면 예상치 못한 오류 발생 가능성 높음
현재 state 값을 newState로 복사 후 사용
function reducer(state, action){
if(state === undefined){
return {
상태명: 초기값
}
const newState = {...state};
return newState;
}
const store = createStore(reducer);
react-redux의 대표기능 4가지
store에 정의 한 state를 어떤 컴포넌트에 제공 할 것인가 정해서 감싸주는 기능
감싼 컴포넌트의 하위 컴포넌트들도 store에 접근가능
Provider에 필수로 props값 store={store} 포함
export default function App() {
return (
<div>
<component1 />
<Provider store={store}>
<component2 />
<component3 />
</Provider>
<component4 />
</div>
)
}
Provider 안에 있는 컴포넌트에서 store state에 접근하게 해주는 함수
useSelector는 함수를 인자로 받음
fucntion 콜백함수(state){
return state.상태명
}
const 변수명 = useSelector(콜백함수);
-----------------------------------
화살표 함수로 변경해서 간단히 사용하가능
const 변수명 = useSelector(state => state.상태명)
컴포넌트에서 useSelector로 가져온 변수를 사용
function component9(props) {
const 사용할변수명 = useSelector(state => state.상태명)
return (
<div>
<h1>불러온 상태값 : {사용할변수명}</h1>
</div>
);
}
Provider 안에 있는 컴포넌트에서 dispatch에 접근하게 해주는 함수
보통 이벤트를 발생시킬때 사용함
dipatch가 호출되면 reducer가 호출됨
const dipatch = useDispatch();
-------------------------------
function component10(props) {
const dipatch = useDispatch();
return (
<div>
<input
type="button"
value="+"
onClick={()=>{
dispatch({type:'PLUS'})
}}
></input>
</div>
);
}
dispatch로 전달한 action값을 참조해서 reducer에 기능 작성
function reducer(state, action){
if(state === undefined){
return {
상태명: 1
}
const newState = {...state};
if(action.type === 'PLUS'){
newState.상태명++
}
return newState;
}
const store = createStore(reducer);
react-redux를 사용해서 변경한 state 값은 해당 컴포넌트에서만 변하는 값으로
다른 컴포넌트를 재랜더링 하지 않음