Redux_5

김종원·2022년 11월 25일
0

[TIL (Today I Learned)]

목록 보기
34/45

장바구니 혹은 상품 id에 따라서 state에 항목을 변경해야 할때!!!
그럴때는 반복문, find(), findIndex()함수를 사용할 수 있습니다.

findIndex()는 array 뒤에 붙일 수 있습니다.
findIndex 안에 콜백함수넣고 return 뒤에 조건식도 넣으면 사용할 수 있습니다.

findIndex( () => {return 조건식} )

findIndex( (a) => {return 조건식} )

a라는 파라미터는 array 안에 있던 자료입니다.
array에 있던 자료를 다 꺼내서 조건식에 대입해보는데 조건식이 참이면 그게 몇번째 자료인지 알려주는 함수입니다.

findIndex( (a) => {return a.id == action.payload} )

그래서 위의 코드는 a.id와 payload가 같으면 그게 몇번째 자료인지 변수에 저장하라는 소리입니다.

let cart = createSlice({
  name : 'cart',
  initialState : [
    {id : 0, name : 'White and Black', count : 2},
    {id : 2, name : 'Grey Yordan', count : 1}
  ],
  reducers : {
    addCount(state, action){
      let num = state.findIndex((a)=>{ return a.id == action.payload })
      state[num].count++
    }
  }
}) 

변수 num에 findIndex로 찾은 자료를 넣어주게 됩니다.

Redux state에 새로운 항목 추가하는 방법

state에 항목을 추가해주는 함수를 만든 뒤 (addItem) push 함수를 통해서 action.payload를 통해 받아온 항목을 state에 넣어줄 수 있습니다.

  • state.push(action.payload)
  • dispatch(addItem( {id : 1, name : 'Red Knit', count : 1}
let cart = createSlice({
  name : 'cart',
  initialState : [
    {id : 0, name : 'White and Black', count : 2},
    {id : 2, name : 'Grey Yordan', count : 1}
  ],
  reducers : {
    addItem(state, action){
      state.push(action.payload)
    }
  }
}) 
<div>
  <button onClick={()=>{
    dispatch(addItem( {id : 1, name : 'Red Knit', count : 1} ))
  }}>주문하기</button>
  </div>
</div> 

끝!!!!!!!!!!!

profile
발전하기위한 기록

0개의 댓글