리액트 redux 활용1

안녕하세요·2024년 1월 2일
0

react

목록 보기
11/32
post-thumbnail

스토어 라이브러리,provider import

import { legacy_createStore as createStore } from 'redux'; //스토어 라이브러리
import { Provider } from 'react-redux';

0. 공유 데이터 정의

const rdata = {name : '홍길동', age : 20}

1. 스토어 호출 함수

function reducer(state = rdata, action) {
  return state
}
 

function reducer(현재상태, 컴포넌트액션처리변수){return state}

2. 스토어 생성 및 리듀서 정의

const store = createStore(reducer);

const store = createStore(호출함수);

3.스토어 사용 범위 지정

root.render(
  <React.StrictMode>
    <Provider store={store}>  {/* 스토어 사용 범위 지정 */}
      <App />
    </Provider>
  </React.StrictMode>
);

컴포넌트에서 useSelector 이용하여 store에 저장된 reducer 함수의 state값 가져오기

app.js 파일

import { useSelector } from 'react-redux';
import './App.css';

function App() {
  //useSelector 이용하여 store에 저장된 reducer 함수의 state값 가져오기
  const state = useSelector(state => state);

  return (
    <div >
      <h1>이름 : {state.name}</h1>
      <h1>나이 : {state.age}</h1>
    </div>
  );
}

export default App;


dispatch를 이용하여 액션 이벤트 함수 처리

index,js에서 스토어 호출 함수에 조건 추가

function reducer(state = rdata, action) {
  if (action.type = 'plus') {
    return {
      name: state.name, age: state.age + 1, addr: state.addr
    }
  }
  return state
}

action.type 이 plus라면 age만 나이를 더먹음 ㅜㅜ

import { useDispatch, useSelector } from 'react-redux';
import './App.css';
import Child1 from './components/Child1';

function App() {
  //useSelector 이용하여 store에 저장된 reducer 함수의 state값 가져오기
  const state = useSelector(state => state);
  
  const dispatch = useDispatch();

  return (
    <div >
      <h1>[App]이름 : {state.name}</h1>
      <h1>[App]나이 : {state.age}</h1>
      <button type='button' onClick={() => dispatch({ type: 'plus' })}>age ++</button>
      <hr />

    </div>
  );
}

export default App;

const dispatch = useDispatch();

선언하고 버튼을 클릭하면 onClick={() => dispatch({ type: 'plus' })} 실행되도록


이제 버튼을 누르면 금새 나이를 먹음

0개의 댓글