개요
1.단일 스토어를 만드는 법
2.리액트에서 스토어 사용법
import redux 하고 액션을 정의하고 사용하는 리듀서를 만들고
리듀서들을 합치고 최종 합쳐진 리듀서를 인자로 단일 스토어를 만든다.
import react-redux conntect 함수를 이용해서 컴포넌트에 연결
1.npm i redux
Action
액션은 객체이다.
두 가지 형태의 액션이 있다.
{type:'TEST'} //payload 없는 액션 , {type:'Test', params:'hello'} //payload 있는 액션
type 만이 필수 프로퍼티이며 type은 문자열
액션을 생서하는 함수를 "액션 생성자(Action Creator 라고 한다.
함수를 통해 액션을 생성해서, 액션 객체를 리턴한다.
createTest('hello'); // {type:'TEST',params:'hello'} 리턴
액션이 하는 일?
액션 생성자를 통해 액션을 만들고 만들어낸 액션 객체를 리덕스 스토어에 보낸다.
리덕스 스토어가 액션 객체를 받으면 스토어의 상태 값이 변경된다. 변경된 상태 값에 의해 상태를 이용하고 있는 컴포넌트가 변경된다.
액션은 스토어에 보내는 일종의 인풋액션을 준비기 위함액션의 타입을 정의하여 변수를 빼는 단계 [강제 X]강제는 아니다. 그냥 타입을 문자열로 넣기에는 실수를 유발할 가능성이 크다. 미리 정의한 변수를 상용하면 스펠링에 주의도 덜 해도 된다.액션 객체를 만들어 내는 함수를 만드는 단계하나의 액션 객체를 만들기 위해 하나의 함수를 만들어 낸다. 액션의 타입은 미리 정의한 타입 변수로 부터 가져와서 사용
const ADD_TODO = "ADD_TODO";
function addTodo(todo) {
return {
type : ADD_TODO,
todo,
};
}
Reducers-리듀서
액션을 주면 그 액션이 적용되어 달라진 결과를 만들어줌
함수이다. pure Function Immutable
리듀서를 통해 스테이트가 달라졌음을 리덕스가 인지하는 방식
액션을 받아서 스테이트를 리턴하는 구조로 인자로 들어오는 previousState 와 리턴되는 newState 는 다른 참조를 가지도록 해야한다.
import {ADD_TODO} from "./actions";
//state ['코딩','점심먹기'];
const initialState = [];
function todoApp(previousState = initialState, action) {
// //초기값을 설정해주는 부분
// if(previousState === undefined) {
// return [];
}
if(action.type === ADD_TODO) {
return [...previousState,action.todo];
}
return previousState;
}
createStore - 스토어 만드는 함수
store.getState(); 현재 스토어의 state를 가져옴
store.dispatch(action) action을 인자로 넣어서 스토어 상태 변환, store.dispatch(액션생성자());
const unsubscribe = store.subscribe(() => {}); 스토어에 변경이 생겼을때 함수 실행
리턴이 unsubscribe 라는 점! unsubscribe(); 하면 제거
store.replaceReducer(다른리듀서);
import { createStore } from "redux";
import { todoApp } from "./reducers";
const store = createStore(todoApp);
export default store;
combineReducers
import { combineReducers } from "redux";
import todos from "./todos";
import filter from "./filter";
const reducer = combineReducers({
todos,
filter,
});
export default reducer;
reducer.js 을 만들고
import { SHOW_COMPLETE, SHOW_ALL } from "../actions";
const initialState = "ALL";
export default function filter(previousState = initialState, action) {
//초기값을 설정해주는 부분
// if (previousState === undefined) {
// return [];
// }
if (action.type === SHOW_COMPLETE) {
return "COMPLETE";
}
if (action.type === SHOW_ALL) {
return "ALL";
}
return previousState;
filter와
import { ADD_TODO, COMPLETE_TODO } from "../actions";
const intitialState = [];
export default function todos(previousState = intitialState, action) {
//초기값을 설정해주는 부분
// if (previousState === undefined) {
// return [];
// }
if (action.type === ADD_TODO) {
return [...previousState, { text: action.text, done: false }];
}
if (action.type === COMPLETE_TODO) {
return previousState.map((todo, index) => {
if (index === action.index) {
return { ...todo, done: true };
}
return todo;
});
}
return previousState;
}
todos를 만들어주어서 따로 분리하여 사용할 수 있다.
Redux를 React에 연결
단일 store를 만들고, subscribe 와 getstate 를 이용하여 변경되는 state 데이터를 얻어 props 로 계속 아래로 전달