Redux
Redux의 구조
redux의 구성 요소는 4가지로 볼 수 있다.
render함수, action객체, reducer 함수, store, middleware
ui를 구성하는 render함수에서 state를 어떻게 해달라는 action을 dispatch함수를 통해 reducer에 전달 한다.
action객체 안에는 type과, payload를 전달 할 수 있다. type은 어떤 일을 해달라고 하는 것인지 입력해 주고, 특정 값을 전달할 필요가 있을 때 payload를 전달한다.
action을 전달 받은 reducer는 전달 받은 action에 맞게 state를 변경하여 새롭게 변경된 state를 리턴 한다.
예제
1.먼저 store를 만들어야 하는데 store 만들 때 reducer함수를 같이 전달해 줘야 하므로 먼저 reducer함수를 만들고 store에 전달해 보자.
<script>
// 1. reducer함수를 만들어 주었고
function reducer(state, action) {
// 아래와 같은 방식으로 state 초기값 설정
if (state === undefined) {
return { color: 'orange' }
}
}
// 2. Redux.createStore로 store만들 때 reducer함수를 전달 했다.
const store = Redux.createStore(reducer)
console.log(store.getState()) // {color: 'orange'}
</script>
2. 간단한 html을 만들어 현재 store에 저장된 state를 배경색으로 지정해 보자
<body>
<div id="practice"></div>
<script>
function reducer(state, action) {
// 아래와 같은 방식으로 초기값 설정
if (state === undefined) {
return { color: 'orange' }
}
}
const store = Redux.createStore(reducer)
// test라는 함수를 만들어서 id가 practice인 요소에 div를 하나 추가 하고 해당 div의 색을
// store에 저장된 state로 지정
function test () {
let state = store.getState()
document.querySelector('#practice').innerHTML = `
<div style="background-color:${state.color}">
<h1> TEST </h1>
</div>
`
}
test ()
</script>
</body>
3. 이번에는 직접 state를 바꾸지 말고 dispatch를 이용해서 state를 변경해 보자.
// 먼저 innerHTML에 버튼을 하나 추가 하여 해당 버튼을 클릭하면 dispatch함수를 호출 하고
// action객체를 전달 하였다.
document.querySelector('#practice').innerHTML = `
<div style="background-color:${state.color}">
<h1> TEST </h1>
<input
type="button"
value='change'
onClick='store.dispatch({type:'CHANGE_COLOR', color: 'blue'})'
>
</div>
`
function reducer(state, action) {
console.log(action) // {type: '@@redux/INIT1.s.x.y.3.6'}
if (state === undefined) {
return { color: 'orange' }
}
}
function reducer(state, action) {
let newState
if (state === undefined) {
return { color: 'orange' }
// action의 타입이 CHANGE_COLOR면 기존의 state를 복사한 다음 color를 전달 받은
// action.color로 바꿔 state를 변경한다. 이렇게 복사를 하는 이유는 불변성을 유지하기 위함
} else if (action.type === 'CHANGE_COLOR') {
newState = Object.assign({}, state, {color: action.color})
}
return newState
}
// 기존 로직을 함수로 만들고
function test () {
let state = store.getState()
document.querySelector('#practice').innerHTML = `
<div style="background-color:${state.color}">
<h1>TEST</h1>
<input type='button' value='blue' onclick="store.dispatch({type:'CHANGE_COLOR', color: 'blue'})">
</div>
`
}
test()
// store.subscribe에 넣어 주면 된다.
store.subscribe(test)
combineReducers