React use Reducter 정보
useReducter 정보
use Reducter는use State와 유사한 물건입니다.(state, action)=>new State형의 리셋을 받아들여 현재state와dispatch 함수를 맞춥니다.
const [state, dispatch] = useReducer(reducer, initialArg, init);
사용 예
다음은 방정식 문서의 예입니다.
실현 내용은 단추를 통해 계수기 값을 +1,-1로 할 수 있는 구성 요소입니다.
우선 다음 코드는 단추를 통해 계수기 값 +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>
이상.읽어주셔서 감사합니다.만약 오자, 누자, 오류 등이 있으면 메시지를 남겨 주세요.
Reference
이 문제에 관하여(React use Reducter 정보), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://zenn.dev/hitoshiasano/articles/91f7f4edc46360텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)