index.js
import App from './App';
import store from './store/store';
import { Provider } from 'react-redux';
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
store.js
import { createStore } from "redux";
import rootReducer from '../reducers/index';
const store = createStore(rootReducer);
export default store;
reducers/index.js
import { combineReducers } from 'redux';
import aReducer from './aReducer';
import bReducer from './bReducer';
const rootReducer = combineReducers({
aReducer,
bReducer
});
export default rootReducer;
reducers/aReducer.js
import { ADD, REMOVE, RENEW } from "../actions/index";
import { initialState } from "./initialState";
const aReducer = (state = initialState, action) => {
switch(action.type){
case ADD:
return Object.assign({}, state, {
a : [...state.a, action.payload]
});
break;
case REMOVE:
return Object.assign({}, state, {
a : state.a.filter((el) =>
el.id !== action.payload.id)
});
break;
case RENEW:
return Object.assign({}, state, {
a : state.a.map((el) => {
if(el.id === action.payload.id){
return action.payload;
}else{
return el;
}
})
});
break;
let idx = state.a.findIndex((el) =>
el.id === action.payload.id);
return Object.assign({}, state, {
a : [
...state.a.slice(0, idx),
action.payload,
...state.a.slice(idx + 1)
]
});
break;
default:
return state;
}
}
export default aReducer;
actions/index.js
export const ADD = "ADD";
export const REMOVE = "REMOVE";
export const RENEW = "RENEW";
export const add = (id) => {
return {
type: ADD,
payload : {
count: 1,
id
}
}
}
export const remove = (id) => {
return {
type: REMOVE,
payload: {
id
}
}
}
export const renew = (id, count) => {
return {
type: RENEW,
payload: {
id,
count
}
}
}
App.js
import { useDispatch, useSelector } from "react-redux";
import { add, remove, renew } from "../actions";
export default function App(){
const state = useSelector(state => state.aReducer);
const dispatch = useDispatch();
const addClick = (item) => {
if(!array.map((el) => el.id).includes(item.id)){
dispatch(add(item.id));
}
}
const removeClick = (id) => {
dispatch(remove(id));
}
const renewClick = (id, count){
dispatch(renew(id, count));
}
return (
<div className="box">
{base.map((item, idx) => (
<div key={idx}>
<div onClick={()=>addClick(item)}></div>
<div onClick={()=>removeClick(idx)}></div>
<input onChange={(e)=>
renewChange(e.target.value, idx)
}/>
</div>
))}
</div>
);
}