Redux - (1)index.js 세팅 및 state 사용하기

Apeachicetea·2021년 11월 28일
0

Redux

목록 보기
1/5

Redux 사용 이유

  1. 깊은 하위컴포넌트들도 props 없이 모든 컴포넌트가 state를 갖다쓰기 가능

Redux, React-redux 설치

npm install redux react-redux

Redux 세팅하기(index.js에서)

1 . import { Provider } from 'react-redux';

  • import { createStore } from 'redux';
  1. <Provider>로 <App /> 감싸기
  • Provider에 감싸져있는 하위 컴포넌트들은 state 사용 가능하다.
  1. createStore()안에 state 저장하기

    let store = createStore(()=>{ return [{ id: 0, name: 'jeju', quan: 2 }] });

  2. Provider에 props 전송
    <Provider store = { store }>

//index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

import { Provider } from 'react-redux';
import { createStore } from 'redux';
let store = createStore(()=>{ 
  return [
    { 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 }
  ] });


ReactDOM.render(
  <React.StrictMode>
    <Provider store={ store }>
      <App />
    </Provider>  
  </React.StrictMode>,
  document.getElementById('root')
);


state 사용하기(A.js에서)

컴포넌트에서 store에 있는 state를 쓰려면

  1. function 만들기(객체(props)를 리턴)
  • 이 함수의 역활은 store에 있는 state를 가져오는 역활을 한다.
  • redux store데이터를 가져와서 props로 변환해주는 함수이다.
  • 결국, redux store의 state를 props화 한다.
  1. export default connect(함수명)(컴포넌트명);
  • (import { connect } from 'react-redux';)
  1. 사용할 컴포넌트 인자에 props 넣어주고 state 사용

//A.js

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>
          </tr>
        </thead>
        <tbody>
            {
              props.state.map((el, i)=>{
                return(
                  <tr>
                    <td>{ i }</td>
                    <td>{ el.id }</td>
                    <td>{ el.name }</td>
                    <td>{ el.quan }</td>
                  </tr>
                )
              })
            }
        </tbody>
      </Table>
    </div>
  )
}


function 함수명(state){
  return {
    state: state
  }
}


export default connect(함수명)(A);




profile
웹 프론트엔드 개발자

0개의 댓글