데이터수정하는 reducer

박시하·2021년 12월 1일
0

React

목록 보기
15/17

데이터수정하는 reducer

function reducer(){
  return [{id : 0, name : '멋진신발', quan : 2}]
}
let store = createStore(reducer);
function reducer(state = 기본state, 액션){
  if (액션.type === '수량증가') {
    return 수량증가된새로운state
  } else {
    return state
  }
  1. '수량증가'라는 데이터 수정방법 이름을 하나 작명합니다. (액션.type === 수정방법이름)
  2. if문 안에는 '수량증가'라는 요청이 들어올 경우 어떤 state를 내보낼지 정의.
  3. else문 안에는 수량증가 요청이 안들어온 경우 기본 state를 내보낼지 정의.
<button onClick={()=>{ props.dispatch({type: '수량증가'}) }}> + </button>

버튼 누를 때마다 '수량증가'라는 버튼이 완성됩니다

let copy = [...state];
   copy[0].quan++;
   return copy

state 데이터 카피본을 만들어서 quan 항목에 1을 더해주고 그걸 return 내보냅니다

reducer 하나 더 만들기

reducer에는 state 초기값 + state 수정하는 법을 넣으면 됩니다.

function reducer2(state = alert초기값, 액션){
  return state
}
let store = createStore( combineReducers({reducer, reducer2}) )

combineReducers() 라는 함수를 하나 'redux'에서 import 해오시고
combineReducers() 안에 모든 리듀서를 object 형식으로 쭉 담으시면 끝

function state를props화(state){
  console.log(state);
  return {
    state : state.reducer,
    alert열렸니 : state.reducer2 //리듀서2에 있는거 가져오는법
  }
}
export default connect(state를props화)(Cart);

❗ state를 props로 저장할땐
state.reducer 라는 데이터는 state라고 저장하고 state.reducer2라는 데이터는 alert열렸니라고 저장했습니다. reducer가 여러개면 store에서 받아오는 데이터의 형식이 달라진다는 것만 참고

profile
기본 회원

0개의 댓글