어떻게 React Hooks 를 사용 하여 우아 하 게 데 이 터 를 얻 습 니까?
인터페이스 에 데 이 터 를 요청 하고 현재 페이지 에 옮 겨 다 니 며 렌 더 링 하려 면 이렇게 쓸 수 있 습 니 다.
import React, {
useState, useEffect } from 'react';
import axios from 'axios';
function App() {
const [data, setData] = useState({
hits: [] });
useEffect(() => {
const fetchData = async () => {
const result = await axios(
'https://hn.algolia.com/api/v1/search?query=redux',
);
setData(result.data);
};
fetchData();
}, []);
return (
//
{
data.hits}
);
}
export default App;
주소 의 조회 파 라 메 터 를 수정 하려 면 입력 상자 와 제출 단 추 를 누 르 십시오.단 추 를 눌 렀 을 때 url 을 바 꾸 어 부작용 으로 새로운 데 이 터 를 끌 어 옵 니 다. 코드 는 다음 과 같 습 니 다.
export default function BestFetchData() {
const [data, setData] = useState(0)
const [query, setQuery] = useState('')
const [url, setUrl] = useState('http://wthrcdn.etouch.cn/weather_mini?city= ')
useEffect(() => {
const fetchData = async () => {
const ret = await axios(url)
setData(ret.data.data)
}
fetchData()
}, [url])
return (
<div>
<h3> </h3>
<input value={
query} onChange={
e => setQuery(e.target.value)} />
<button type='button' onClick={
() => setUrl('http://wthrcdn.etouch.cn/weather_mini?city=' + query)}> </button>
{
data && <>
//
</>}
</div>
)
}
다음 단 계 는 loading 과 오류 캡 처 기능 을 추가 하고 폼 제출 이 벤트 를 통 해 검색 을 실현 합 니 다.
export default function () {
const [data, setData] = useState('')
const [query, setQuery] = useState('')
const [url, setUrl] = useState('http://wthrcdn.etouch.cn/weather_mini?city= ')
const [isLoading, setIsLoading] = useState(false)
const [isError, setIsError] = useState(false)
useEffect(() => {
const fetchData = async () => {
setIsLoading(true)
setIsError(false)
try{
const ret = await axios(url)
setData(ret.data.data)
}catch(e){
setIsError(true)
}
setIsLoading(false)
}
fetchData()
}, [url])
return (
<div>
<h3>loading+ + </h3>
<p> </p>
<form onSubmit={
(e) =>{
e.preventDefault(); setUrl('http://wthrcdn.etouch.cnn/weather_mini?city2==' + query)}}>
<input value={
query} onChange={
e => setQuery(e.target.value)} />
<button type='submit'> </button>
</form>
{
isError&&<div style={
{
background:'pink',padding:'1rem',margin:'1rem'}}> ~~</div>}
{
data && (isLoading
? <div> loading...</div>
: <>
//
</>)}
</div>
)
}
사용자 정의 hooks 를 사용 하여 요청 과 관련 된 논 리 를 패키지 하여 재 활용 할 수 있 습 니 다.useFetchData 는 논리 적 처리 에 만 신경 쓰 고 데이터 에 관심 이 없다.
const useFetchData = (initialUrl, initialData) => {
const [url, setUrl] = useState(initialUrl)
const [data, setData] = useState(initialData)
const [isLoading, setIsLoading] = useState(false)
const [isError, setIsError] = useState(false)
useEffect(() => {
const fetchData = async () => {
setIsLoading(true)
setIsError(false)
try {
const ret = await axios(url)
setData(ret.data.data)
} catch (e) {
setIsError(true)
}
setIsLoading(false)
}
fetchData()
}, [url])
return [{
data, isLoading, isError }, setUrl]
}
export default function () {
const [query, setQuery] = useState('')
const [{
data, isLoading, isError }, doFetch] = useFetchData('http://wthrcdn.etouch.cn/weather_mini?city= ', null)
return (
<div>
<h3> hooks </h3>
<p> </p>
<form onSubmit={
(e) => {
e.preventDefault(); doFetch('http://wthrcdn.etouch.cn/weather_mini?city=' + query) }}>
<input value={
query} onChange={
e => setQuery(e.target.value)} />
<button type='submit'> </button>
</form>
{
isError && <div style={
{
background: 'pink', padding: '1rem', margin: '1rem' }}> ~~</div>}
{
data && (isLoading
? <div> loading...</div>
: <>
//
</>)}
</div>
)
}
reducer 를 사용 하여 사용자 정의 hook 에서 비교적 독립 된 논 리 를 다시 밀봉 할 수 있 습 니 다.
const dataFetchReducer = (state, action) => {
switch (action.type) {
case 'FETCH_INIT':
return {
...state, isLoading: true, isError: false }
case 'FETCH_SCUESS':
return {
...state, isError: false, isLoading: false, data: action.payload }
case 'FETCH_FAILURE':
return {
...state, isLoading: false, isError: true }
default:
throw new error();
}
}
const useDataApi = (initialUrl, initialData) => {
const [state, dispatch] = useReducer(dataFetchReducer, {
data: initialData,
isLoading: false,
isError: false
})
const {
data, isLoading, isError } = state
const [url, setUrl] = useState(initialUrl)
useEffect(() => {
const fetchData = async () => {
dispatch({
type: 'FETCH_INIT' })
try {
const ret = await axios(url)
dispatch({
type: 'FETCH_SCUESS', payload: ret.data.data })
} catch (e) {
dispatch({
type: 'FETCH_FAILURE' })
}
}
fetchData()
}, [url])
return [state, setUrl]
}
export default function () {
const [query, setQuery] = useState('')
const commonUrl = 'http://wthrcdn.etouch.cn/weather_mini?city='
const [{
data, isLoading, isError }, doFetch] = useDataApi(commonUrl + ' ', null)
return (
<div>
<h3> reducer</h3>
<p> </p>
<form onSubmit={
(e) => {
e.preventDefault()
doFetch(commonUrl + query)
}}>
<input value={
query} onChange={
e => setQuery(e.target.value)} />
<button type='submit'> </button>
</form>
{
isError && <div style={
{
background: 'pink', padding: '1rem', margin: '1rem' }}> ~~</div>}
{
data && (isLoading
? <div> loading...</div>
: <>
//
</>)}
</div>
)
}
끝나다
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
html 5 마우스 멋 진 사이트 안내 페이지 애니메이션 효과 따라 가기html 5 마우스 멋 진 사이트 안내 페이지 애니메이션 효 과 를 따라 아주 좋 은 안내 페이지 입 니 다. 문자 효과 가 점점 변 하고 마 우 스 는 화려 한 스 트 라 이 프 를 따라 갑 니 다.html 5 시...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.