React의 useReducer 후크 사용 사례
                                            
                                                
                                                
                                                
                                                
                                                
                                                 7419 단어  stateusereducerreacthooks
                    
세 가지입니다.
비녀장
상태를 전환하고 싶을 때 상태가 부울인 경우 다음을 수행할 수 있습니다.
import {useReducer} from 'react'
export const useToggle= (initialState=false)=>{
  const [isSomething, toogleIsSomething]= useReducer(state=> !state, initialState)
  return [isSomething,toggleIsSomething]
}
따라서 이 후크를 사용하고 싶을 때마다 다음을 수행할 수 있습니다.
function SomeComponent(){
  const [isSome, toogleIsSome]=useToggle()
  return ...
}
export default SomeComponent
업데이트
또 다른 사용 사례는 상태를 업데이트하려는 경우입니다. 그렇게 할 수 있습니다.
import {useReducer} from 'react'
export const useUpdate= (initialState={})=> {
  const [state, updateState]= useReducer((state, obj)=>({...state, ...obj}), initialState)
  return [state, updateState]
} 
다음과 같이 사용할 수 있습니다.
function AnotherComponent(){
  const [state, updateState]= useUpdate({c:3})
  const someHandler= ()=>{
    updateState({a:1,b:2}) // after that state will be {a:1, b:2, c:3}
  }
  return ...
}
export default AnotherComponent
보내다
그런 다음 리듀서 함수의 두 번째 매개변수로 액션을 전달하고 결과적으로 디스패치 함수를 얻는 일반적인 사용 사례가 있습니다.
const reducer=(state, action)=>{
  switch(action.type){
    case 'UPDATE':
      return {...state, ...action.payload}
    default:
      return state
  }
}
function ThirdComponent(){
  const [state, dispatch]= useReducer(reducer,{c:3})
  const someHandler= ()=> {
    dispatch({type:'SOMETHING', payload: {a:1, b:2}})
  }
  return ...
}
export default ThirdComponent
이 게시물에 제시되지 않은 다른 사용 사례가 있으면 댓글로 남겨주시면 좋을 것 같습니다.
감사.
Reference
이 문제에 관하여(React의 useReducer 후크 사용 사례), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/roggc/usereducer-hook-use-cases-in-react-481i텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
                                
                                
                                
                                
                                
                                우수한 개발자 콘텐츠 발견에 전념
                                (Collection and Share based on the CC Protocol.)