반응 후크 사용
반응 후크 란 무엇입니까?
Hooks는 React 16.8에 추가되었으며 상태를 사용할 수 있게 해줍니다.
클래스를 작성하지 않고 다른 수명 주기 메서드,
기능적 구성 요소만 사용할 수 있습니다.
"후크가 단순히 기능을 대체하는 것이라면 애초에 후크를 사용하는 이유는 무엇입니까?"라고 물을 수 있습니다.
클래스 구성 요소를 사용하는 동안 이미 가지고 있었던 것입니다!", 하지만 그렇지 않습니다. Hooks에는 많은 기능이 포함되어 있습니다.
클래스 구성 요소에서 사용되는 수명 주기 메서드에 대한 개선 사항입니다.
React Hooks를 사용하면 이전 패턴보다 훨씬 우아한 방식으로 교차 절단 문제를 해결할 수 있습니다.
higher-order components과 같은
및 render props .
로깅 및 인증과 같은 기능은 구성 요소에 따라 다르며 React Hooks를 사용하면 이러한 유형의 재사용 가능한 동작을 구성 요소에 연결할 수 있습니다.
이 블로그 게시물에서는 두 가지 가장 중요한 후크(useState 및 useEffect)를 사용하는 방법을 보여 드리겠습니다.
클래스 없는 반응 앱을 빌드해야 합니다.
이 공개 API
api: https://v2.jokeapi.dev/joke/Any
useState
이 방법을 사용하면 기능적 구성 요소에서 상태를 사용할 수 있습니다.
상태와 해당 상태를 변경하는 메서드가 있는 배열을 반환합니다.
const [state,setState] = useState();
// state will have the initial state in this case undefined
// setState is the function that we can use to update the state
상태를 업데이트하려면
setState("words")
// you would use it as such,
//the parameter takes in the value you want to update the state with
우리 앱에서는 create-react-app과 함께 제공되는 기본 설정을 사용합니다.
다음과 같이 업데이트하십시오.
import {useState} from 'react';
import './App.css';
function App() {
//we created a state joke that is intialized with a string value for now
const [joke,setJoke] = useState("There are only 10 kinds of people in this world: those who know binary and those who don't.")
return (
<div className="App">
<header className="App-header">
<h3>{joke}</h3>
</header>
</div>
);
}
export default App;
이제 우리 앱은 이렇게 생겼습니다 !🤘
(재미있는 농담이라고 해야겠네요)
useEffect
React Hooks는 대체할
useEffect()
메서드를 도입했습니다.클래스 구성 요소의 수명 주기 메서드
componentDidMount
, componentDidUpdate
및 componentWillUnmount
.이 방법은 또한 기능적 구성 요소에 부작용을 허용합니다.
문서 개체 모델의 콘텐츠 변경 및 데이터 가져오기와 같은
useEffect()
는 모든 구성 요소가 렌더링된 후 실행됩니다.Reacts 문서에서
useEffect Accepts a function that contains imperative, possibly effectful code.
Mutations, subscriptions, timers, logging, and other side effects are not allowed
inside the main body of a function component (referred to as React’s render phase).
Doing so will lead to confusing bugs and inconsistencies in the UI.Instead, use useEffect. The function passed to useEffect will run after the render
is committed to the screen. Think of effects as an escape hatch from React’s purely
functional world into the imperative world.By default, effects run after every completed render,
but you can choose to fire them only when certain values have changed.
그것은 받아 들여야 할 것이 많습니다!
효과적인 코드가 무엇인지 설명하면서 시작하겠습니다. !
효과적인 코드는 함수 범위 밖의 무언가에 영향을 미치는 코드입니다.
실행되고 있는 것, 부작용이라고도 함
다음과 같은 경우 부작용이 관찰될 수 있습니다.
//Example
useEffect(()=>{
fetchData() // making a network request
//eveythig inside this function will be called on every render
//fetchData() will be called everytime the component re-renders
})
useEffect
종속성 배열을 두 번째 매개변수로 사용합니다.이렇게 하면 원할 때만 실행되도록 할 수 있습니다.
Jokes 앱에서 임의의 농담 API를 사용하여 렌더링할 때마다 상태를 업데이트하려고 합니다.
이를 위해
useEffect()
메서드와 setJoke()
에서 가져온 useState()
메서드를 사용합니다.import {useState, useEffect} from 'react';
import './App.css';
function App() {
const [joke,setJoke] = useState("")
useEffect(()=>{
getRandomJoke();
})
//fetching the data and setting and updating state
const getRandomJoke = async () => {
const response = await fetch("https://v2.jokeapi.dev/joke/Any?type=single");
const result = await response.json();
if(!result.error){
setJoke(result.joke);
}
}
return (
<div className="App">
<header className="App-header">
<h3>{joke}</h3>
</header>
</div>
);
}
export default App;
재미있는 것은 농담이 바뀌는 것 같습니다! 하지만 멈추지 않는다!
useEffect()
메서드는 joke
상태가 변경될 때마다 실행되므로 실행됩니다.무한 루프에서 !
종속성 배열을 사용하도록 수정하려면 첫 번째 렌더링에서만 실행되기를 원합니다.
그래서 우리는 이와 같은 빈 배열을 전달할 것입니다
useEffect(()=>{
getRandomJoke();
},[]) //passed an empty array []
(농담을 즐기세요!)
이렇게 하면 문제가 해결되어 이제 첫 번째 렌더링에서만 실행됩니다!
끝까지 달려주셔서 감사합니다👍 !
다루어야 할 더 많은 정보가 있지만 나중에 보관하겠습니다(다른 블로그 게시물).
공식 확인documentation
랜덤 농담 생성기here에 대한 github 저장소를 찾을 수 있습니다.
Reference
이 문제에 관하여(반응 후크 사용), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/bassel17/using-react-hooks-4ejl텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)