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