후크가 반응하는 API 호출은 어디서 할 수 있나요?
으로는 API 은 API에서 합니다.componentDidMount()
에서의 라이프 : 리액트 클래스 컴포넌트는 다음과 .
componentDidMount(){
//Here we do API call and do setState accordingly
}
그러나 React v16.7.0에서 후크가 도입된 후에는 대부분 기능 컴포넌트와 동일합니다.
질문입니다만, 훅이 있는 기능 컴포넌트에서 API 호출을 하려면 정확히 어디서 해야 합니까?
componentDidMount()
componentDidMount
훅이 .useEffect
다른 답변은 API 호출을 어디서 할 수 있는지에 대한 질문에 대한 답변이 아닙니다.은 API를 하여 할 수 .useEffect
빈 배열 또는 오브젝트를 두 번째 인수로 전달하여 대신합니다.componentDidMount()
이치인수로 빈 또는 모든 API가 .componentDidUpdate
.
문서에서 설명한 바와 같이:
빈 입력 배열 []을 전달하면 React에 영향이 컴포넌트의 값에 의존하지 않는다는 것을 알 수 있습니다.따라서 이 효과는 마운트 시에만 실행되고 마운트 해제 시 청소되며 업데이트 시 실행되지 않습니다.
다음으로 API 호출이 필요한 시나리오의 예를 제시하겠습니다.
마운트에서의 API 콜은 엄밀하게
아래 코드를 실행하여 결과를 확인하십시오.
function User() {
const [firstName, setFirstName] = React.useState(null);
const [lastName, setLastName] = React.useState(null);
React.useEffect(() => {
fetch('https://randomuser.me/api/')
.then(results => results.json())
.then(data => {
const {name} = data.results[0];
setFirstName(name.first);
setLastName(name.last);
});
}, []); // <-- Have to pass in [] here!
return (
<div>
Name: {!firstName || !lastName ? 'Loading...' : `${firstName} ${lastName}`}
</div>
);
}
ReactDOM.render(<User />, document.querySelector('#app'));
<script src="https://unpkg.com/react@16.7.0-alpha.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script>
<div id="app"></div>
Prop/State가 변경될 때마다 API 호출
예를 각 가 있는 사용자의 ID prop은 ID state/prop의 두 파라미터에 .useEffect
데이터가 새 사용자 ID에 맞게 다시 지정되도록 합니다. componentDidMount
사용자 A에서 사용자 B의 프로파일로 직접 이동하면 컴포넌트를 다시 마운트할 필요가 없기 때문에 여기서는 불충분합니다.
기존의 수업 방식으로는 다음과 같이 할 수 있습니다.
componentDidMount() {
this.fetchData();
}
componentDidUpdate(prevProps, prevState) {
if (prevState.id !== this.state.id) {
this.fetchData();
}
}
후크를 사용하면 다음과 같습니다.
useEffect(() => {
this.fetchData();
}, [id]);
아래 코드를 실행하여 결과를 확인하십시오. ID를 하여 ID가 2인지 합니다.useEffect
시시시실실실다다
function Todo() {
const [todo, setTodo] = React.useState(null);
const [id, setId] = React.useState(1);
React.useEffect(() => {
if (id == null || id === '') {
return;
}
fetch(`https://jsonplaceholder.typicode.com/todos/${id}`)
.then(results => results.json())
.then(data => {
setTodo(data);
});
}, [id]); // useEffect will trigger whenever id is different.
return (
<div>
<input value={id} onChange={e => setId(e.target.value)}/>
<br/>
<pre>{JSON.stringify(todo, null, 2)}</pre>
</div>
);
}
ReactDOM.render(<Todo />, document.querySelector('#app'));
<script src="https://unpkg.com/react@16.8.1/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.8.1/umd/react-dom.development.js"></script>
<div id="app"></div>
당신은 그것을 가지고 무엇을 할 수 있는지 알 수 있도록 계속 읽어야 합니다.
서스펜스
Dan Abramov가 이 GitHub 이슈에서 말한 것처럼:
장기적으로는 이 (use Effect) 패턴이 레이스 조건을 촉진하기 때문에 권장하지 않습니다.예를 들어, 상담 시작과 종료 사이에 무슨 일이 일어나거나 새로운 소품을 얻을 수도 있습니다.대신 데이터 가져오기에는 서스펜스를 권장합니다.
Suspension 많이 봐주세요!
저의 노력을 이해하기 위한 간단한 방법으로 글을 올립니다.Yangshun Tay의 게시물이 거의 모든 것을 커버하고 있다는 것은 칭찬할 만하다.
컴포넌트 마운트 API 호출
코드:
useEffect(() => {
// here is where you make API call(s) or any side effects
fetchData('/data')
}, [] ) /** passing empty brackets is necessary */
이렇게 쓰면서useEffect(fn,[])
를 「」로 합니다.[]
만들다fn()
컴포넌트가 값을 사용하지 않고 작성(예:) 및 파기(예:)할 때 전체에 걸쳐 한 번 트리거됩니다.
프로 팁:
, ★★★★★★★★★★★★★★★★★★★★★★return()
안에 것fn
하면 하게 됩니다.componentWillUnmount()
클래스 컴포넌트로서의 라이프 사이클.
useEffect(() => {
fetchData('/data')
return () => {
// this will be performed when component will unmount
resetData()
}
}, [] )
값이 변경되면 API 호출
변경되었을 때는, 그 변수 것)를, 「」의 「API」( 「」)의 Arguments .useEffect()
.
useEffect(() => {
// perform your API call here
updateDetails();
},[prop.name]) /** --> will be triggered whenever value of prop.name changes */
에 의해, 「」의 값이 「」의 어느 라도, 됩니다.prop.name
이치노
또한 주의: 이 후크는 컴포넌트가 장착될 때 처음에 호출됩니다.따라서 이 때 이름 값은 의도하지 않은 초기 상태일 수 있습니다.따라서 불필요한 API 호출을 피하기 위해 함수에 커스텀 조건을 추가할 수 있습니다.
https://resthooks.io과 같이 후크를 제공하는 라이브러리를 사용할 수 있습니다.
그 후, 다음과 같이 간단하게 데이터를 입수할 수 있습니다.
const article = useSuspense(ArticleResource.get, { id });
이제 당신은 아이디로 기사를 잡았군요.행복하지 않은 모든 경로(로드, 오류 상태)는 각각 보류 및 오류 경계에 의해 처리됩니다.
다음의 간단한 가이드를 참조해 주세요.https://resthooks.io/docs/getting-started/installation
단 7kb gzipp로 큰 수고를 덜 수 있으며, 코드 반복이 적기 때문에 장기적으로는 번들 크기를 줄일 수 있습니다.
API에서 를 할 수 .useEffect()
으로 인해 렌더링됩니다.이러한 부작용으로 인해 상태가 업데이트될 때마다 구성 요소가 다시 렌더링됩니다.
문서의 예.
import { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
// Similar to componentDidMount and componentDidUpdate:
useEffect(() => {
// Update the document title using the browser API
document.title = `You clicked ${count} times`;
});
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
를 들어 '어느 정도', '어느 정도'라고 부를 수 요.setCount
비동기 요구의 콜백 함수에서 사용됩니다.콜백이 실행되면 상태가 갱신되고 React가 컴포넌트를 다시 렌더링합니다.한한: :
팁.
의 라이프 방법을 알고 을 React로 생각할 수 .
componentDidMount
,componentDidUpdate
, , , , 입니다.componentWillUnmount
★★★★★★★★★★★★★★★★★★.
다음과 같은 것도 사용할 수 있습니다.
import useFetch from 'use-http'
function App() {
// add whatever other options you would add to `fetch` such as headers
const options = {
method: 'POST',
body: {}, // whatever data you want to send
}
var [data, loading, error] = useFetch('https://example.com', options)
// want to use object destructuring? You can do that too
var { data, loading, error } = useFetch('https://example.com', options)
if (error) {
return 'Error!'
}
if (loading) {
return 'Loading!'
}
return (
<code>
<pre>{data}</pre>
</code>
)
}
언급URL : https://stackoverflow.com/questions/53219113/where-can-i-make-api-call-with-hooks-in-react
'programing' 카테고리의 다른 글
angularjs를 사용하여 저장되지 않은 데이터 감지 (0) | 2023.03.15 |
---|---|
그물 잡는 법:ERR_CONNECTION_REFUSED (0) | 2023.03.15 |
각도 2 단위 테스트: 'descript' 이름을 찾을 수 없습니다. (0) | 2023.03.15 |
div 클래스의 마지막 아이 (0) | 2023.03.15 |
sqldeveloper의 insert 문장에서 BLOB 열에 삽입하려면 어떻게 해야 합니까? (0) | 2023.03.15 |