React use Reducter 정보

12491 단어 Reacthooktech

useReducter 정보


use Reducter는use State와 유사한 물건입니다.(state, action)=>new State형의 리셋을 받아들여 현재state와dispatch 함수를 맞춥니다.
const [state, dispatch] = useReducer(reducer, initialArg, init);

사용 예


다음은 방정식 문서의 예입니다.
실현 내용은 단추를 통해 계수기 값을 +1,-1로 할 수 있는 구성 요소입니다.
https://ja.reactjs.org/docs/hooks-reference.html#usereducer
우선 다음 코드는 단추를 통해 계수기 값 +1,-1을 증가시킬 수 있는 구성 요소입니다.
const initialState = {count: 0};

function reducer(state, action) {
  switch (action.type) {
    case 'increment':
      return {count: state.count + 1};
    case 'decrement':
      return {count: state.count - 1};
    default:
      throw new Error();
  }
}

function Counter() {
  const [state, dispatch] = useReducer(reducer, initialState);
  return (
    <>
      Count: {state.count}
      <button onClick={() => dispatch({type: 'decrement'})}>-</button>
      <button onClick={() => dispatch({type: 'increment'})}>+</button>
    </>
  );
}

상태의 초기 값 정의


먼저 상태의 초기 값을 정의합니다.
const initialState = {count: 0};

로드 정의


그리고 use Reducter에 납품될 유용기를 정의합니다.현재 상태 값state과 디스패치 함수 매개 변수로 전달action을 매개 변수로 새 상태 값을 되돌려주는 함수입니다.
납품된 action.type에 따라 새로운 상태가 바뀌었다.
function reducer(state, action) {
  switch (action.type) {
    case 'increment':
      return {count: state.count + 1};
    case 'decrement':
      return {count: state.count - 1};
    default:
      throw new Error();
  }
}

useReducer


useReducter를 사용하여 상태 및 dispatch 함수를 정의합니다.
const [state, dispatch] = useReducer(reducer, initialState);

버튼 설치


다음은 계수기의 감법 버튼을 설명한다.클릭하면 디스패치가 매개 변수{type: 'decrement'}로 이동합니다.내부는 Reducteraction.type='decrement'로 처리됩니다.결과state.count의 값-1.
<button onClick={() => dispatch({type: 'decrement'})}>-</button>
계수기를 추가하는 버튼도 위와 같습니다. 클릭하면 디스패치가 매개 변수{type: 'increment'}로 이동합니다.내부는 Reducteraction.type='increment'로 처리됩니다.결과state.count의 값이 +1이다.
<button onClick={() => dispatch({type: 'increment'})}>+</button>
이상.읽어주셔서 감사합니다.
만약 오자, 누자, 오류 등이 있으면 메시지를 남겨 주세요.

좋은 웹페이지 즐겨찾기