state 데이터 관리가 용이하다.
redux에선 state데이터의 수정방법을 미리 정의 : reducer 함수
reducer함수는 수정된 state를 리턴해주는 함수이다
let store = createStore(reducer);
기본 데이터를 다른 변수에 할당한다.
let initialValue = [
{ id: 0, name: 'jeju', quan: 2 },
{ id: 1, name: 'gimpo', quan: 5 },
{ id: 2, name: 'seoul', quan: 7 },
{ id: 3, name: 'busan', quan: 1 },
{ id: 4, name: 'deagu', quan: 12 }
]
function reducer(state = initialValue, action) {
let copyValue = [...initialValue];
if(action.type === 'plus'){
if(copyValue[0].quan !== 10) {
copyValue[0].quan++;
return copyValue;
}
else if(copyValue[0].quan === 10) {
copyValue[0].quan = 10
return copyValue;
}
}
else if(action.type === 'minus'){
if(copyValue[0].quan !== 0) {
copyValue[0].quan--;
return copyValue;
}
else if(copyValue[0].quan === 0) {
copyValue[0].quan = 0
return copyValue;
}
}
else {
return state;
}
}
let store = createStore(reducer);
는 reducer 다음에 정의해놔야 정상작동한다.데이터 수정요청을 할 땐 props.dispatch({ type: 액션타입명 })
<td>
<button onClick={ ()=>{ props.dispatch({ type: 'plus' }) } }>+</button>
<button onClick={ ()=>{ props.dispatch({ type: 'minus' }) } }>-</button>
</td>
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
let initialValue = [
{ id: 0, name: 'jeju', quan: 2 },
{ id: 1, name: 'gimpo', quan: 5 },
{ id: 2, name: 'seoul', quan: 7 },
{ id: 3, name: 'busan', quan: 1 },
{ id: 4, name: 'deagu', quan: 12 }
]
function reducer(state = initialValue, action) {
if(action.type === 'plus'){
let copyValue = [...initialValue];
copyValue[0].quan++;
return copyValue;
}
else if(action.type === 'minus'){
let copyValue = [...initialValue];
copyValue[0].quan--;
return copyValue;
}
else {
return state;
}
}
let store = createStore(reducer);
ReactDOM.render(
<React.StrictMode>
<Provider store={ store }>
<App />
</Provider>
</React.StrictMode>,
document.getElementById('root')
);
import React from 'react';
import { Table } from 'react-bootstrap';
import { connect } from 'react-redux';
function A(props){
return (
<div>
<Table striped bordered hover>
<thead>
<tr>
<th>#</th>
<th>id</th>
<th>Name</th>
<th>Quan</th>
<th>Set</th>
</tr>
</thead>
<tbody>
{
props.state.map((el, i)=>{
return(
<tr key={ i }>
<td>{ i }</td>
<td>{ el.id }</td>
<td>{ el.name }</td>
<td>{ el.quan }</td>
<td>
<button onClick={ ()=>{ props.dispatch({ type: 'plus' }) } }>+</button>
<button onClick={ ()=>{ props.dispatch({ type: 'minus' }) } }>-</button>
</td>
</tr>
)
})
}
</tbody>
</Table>
</div>
)
}
function 함수명(state){
return {
state: state
}
}
export default connect(함수명)(A);