Redux사용의 현재로써 최종형태
기존의 1,2,3,4의 방식도 좋지만 좀더 짧은코드를 사용해 redux store의 state를 꺼내올 수 있다.
useSelector Hook에대해 알아본다.
// store에있던 데이터를 가져와서 props로 변환해주는 함수
// 즉 return에 있는애들이 props 라고 볼 수 있음
// function state를props화(state){
//   console.log(state)
//   return {
//     상품명 : state.reducer[0].name,
//     state:state.reducer,
//     alert열렸니:state.reducer2
//   }
// }
// export default connect(state를props화)(Cart)
export default Cart;
하단에 맨 아랫줄을 이와같이 남겨놓는다.
import { connect, useDispatch, useSelector } from 'react-redux'
function Cart(props){
  let state = useSelector((state)=>state) // redux에있던 모든 state임 => 리턴
  console.log(state)
  console.log(state.reducer)
  // let state = useSelector((state)=>state.reducer) // redux에있던 모든 state임 => 리턴
  // console.log(state)
  let dispatch = useDispatch()
  return(
    
      <div>
      
      .......
let state = useSelector((state)=>state)같이 콜백함수로 redux에 있던 모든 state를 변수로 저장해 사용한다.
즉 뒤에 =>state의 state는 state.reducer, state.reducer2와같이 가져와도된다.
콜백함수내의 state파라미터는 reducer 전부합친것, 뒤에 있는건 원하는대로 가공이 가능하다.
대신 사용할때 그에 맞춰서 사용해야한다.
<tbody>{
      // props.state.map((a,i)=>{
        state.reducer.map((a,i)=>{
        return(
          <tr key = {i}>
        <td>{ a.id }</td>
        <td>{ a.name }</td>
        <td>{ a.quan }</td>
        <td>
        <button onClick={()=>{ dispatch( {type:"수량증가"}) }}>+</button>
        <button onClick={()=>{ dispatch( {type:"수량감소"}) }}>-</button>
        {/* <button onClick={()=>{ props.dispatch( {type:"수량증가"}) }}>+</button>
        <button onClick={()=>{ props.dispatch( {type:"수량감소"}) }}>-</button> */}
        </td>
      </tr>
        )
      })
      }          
    </tbody>
사용할때 이와같이 props가아닌 state.reducer.map으로 사용해준다.
useDispatch()
import { connect, useDispatch, useSelector } from 'react-redux'
function Cart(props){
  let state = useSelector((state)=>state) // redux에있던 모든 state임 => 리턴
  let dispatch = useDispatch()
  
  ..........
그리고 이와같이 useDispatch역시 import해서 사용해야한다.
dispatch라는 변수에 저장해서 사용한다
 <button onClick={()=>{ dispatch( {type:"수량증가"}) }}>+</button>
        <button onClick={()=>{ dispatch( {type:"수량감소"}) }}>-</button>
        {/* <button onClick={()=>{ props.dispatch( {type:"수량증가"}) }}>+</button>
        <button onClick={()=>{ props.dispatch( {type:"수량감소"}) }}>-</button> */}
기존에 props.dispatch라고 사용한것 역시 이와같이 변수로저장한 dispatch만써서 더 간편하게 사용할 수 있다.
이상 전체 과정을 숙지하고 최종형태로 간단한 코드형태로 기억해두도록하자!
'React' 카테고리의 다른 글
| npm start,yarn start 오류 (React proxy관련) (0) | 2022.02.03 | 
|---|---|
| React 내가 다시 볼 쿡북 (0) | 2022.01.18 | 
| React Redux 4 (dispatch 데이터 보내기) (0) | 2022.01.17 | 
| React Redux 3(state,ruducer 여러개만들기) (0) | 2022.01.17 | 
| React Redux 2(reducer,dispatch,state수정) (0) | 2022.01.17 |