리액트-Redux 사용하기.2 - Reducer

dongwon·2021년 5월 16일
0

리덕스(Redux) 상태관리 기능은 액션(Action)이 날라오면 리듀서(Reducer)가 스토어(Store)의 상태(State)를 변경시키는 방식으로 동작합니다.

이번에는 Reducer를 사용해보겠습니다.

이전의 Redux사용 리액트 프로젝트에서 +버튼을 눌렀을때 수량이 증가하도록 state를 변화시키기 위해 Reducer를 사용합니다.
Reducer는 state의 변경(수정)을 정의해두는 부분으로 함수로 만들 수 있습니다.
그리고 dispatch()함수를 이용하여 다른 컴포넌트에서 Reducer함수를 동작시킬 수 있습니다.

reducer함수는 defalut parameter를 사용하여 data.js의 값(Data)을 초기값으로 설정하는 현재상태의 state와 action을 파라미터로 갖고, 전달받은 action의 참고하여 변경 된 상태(state)를 반환합니다.

(index.js)
import React from 'react';
import 블라블라
	.
	.
	.
import {Provider} from 'react-redux'; 
import {createStore} from 'redux';   
import Data from './data.js';   //외부의 데이터 
  

function reducer(state = Data, action){ //reducer함수
  
  if(action.type === 'plus'){ //데이터가 수정되는 HTML화면에서 dispatch되어 'plus'라는 수정 요청이 들어오면 수량이 1증가하는 if문
    let copyData = [...state];  //state의 값을 깊은복사로 copyData리는 변수에 넣습니다.
    copyData[0].count++;   
    return copyData;
  }else{
    return state;
  }
}

let store = createStore(reducer); // 만든 reducer함수를 store에 넣습니다.

//let store = createStore(()=>{  // 기존의 코드는 필요없음.
// return Data 
//});  

 
ReactDOM.render(
  <React.StrictMode>
    <BrowserRouter>
      <Provider store={store}>   
        <App/>
      </Provider store={store}>  
    </BrowserRouter>
  </React.StrictMode>
);

이제 데이터가 수정되는 컴포넌트에 +버튼을 하나 만들고 클릭시 콜백함수를 만듭니다.
콜백함수에는 props.dispatch를 사용하여 데이터의 수정을 요청합니다.
dispatch()함수 안에는 오브젝트가 들어가고 어떤요청을 할지 타입을 정해줍니다. {type:'puls'}

코드 : onClick={()=>{ props.dispatch({type:'plus'}) }}

function CoinTable(props){
  return (
    <div>
      <Table>
        <thead>
          <tr>
            <th>#id</th>
            <th>상품명</th>
            <th>가격</th>
            <th>수량</th>
            <th>변경</th> 
          </tr>
        </thead>
        <tbody>
          {
            props.stateCoin.map((a,i)=>{
              return(
                <tr key={i}>
                  <td>{a.id}</td>
                  <td>{a.title}</td>
                  <td>{a.price}</td>
                  <th>{a.count}</th>
                  <td>
                      <button onClick={()=>{ props.dispatch({type:'plus'}) }}>+</button> //여기 +버튼
                 </td>
                </tr>
              )
            })
          }
        </tbody>
      </Table>
    </div>
  )
}

이제+버튼을 누르면 dispatch를 통해 type이 'plus'인 리듀스함수를 요청하고 store의 state가 변경됩니다.

profile
What?

0개의 댓글