React Hooks - 发出 Ajax 请求 [英] React Hooks - Making an Ajax request
问题描述
我刚刚开始使用 React 钩子,想知道 AJAX 请求应该是什么样子?
我尝试了很多次尝试,但无法使其正常工作,并且也不知道实现它的最佳方法.以下是我最近的尝试:
import React, { useState, useEffect } from 'react';const App = () =>{const URL = 'http://api.com';const [data, setData] = useState({});useEffect(() => {const resp = fetch(URL).then(res => {控制台日志(res)});});返回 (<div>//这里显示内容
)}
您可以创建一个名为 useFetch
的自定义挂钩,该挂钩将实现 useEffect
挂钩.
通过将一个空数组作为第二个参数传递给 useEffect
钩子将触发对 componentDidMount
的请求.
见下面的代码.
import React, { useState, useEffect } from 'react';const useFetch = (url) =>{const [data, setData] = useState(null);//空数组作为第二个参数,相当于 componentDidMountuseEffect(() => {异步函数 fetchData() {const 响应 = 等待 fetch(url);const json = 等待 response.json();设置数据(json);}取数据();}, [网址]);返回数据;};const App = () =>{const URL = 'http://www.example.json';const 结果 = useFetch(URL);返回 (<div>{JSON.stringify(结果)}
);}
I have just began playing around with React hooks and am wondering how an AJAX request should look?
I have tried many attempts, but am unable to get it to work, and also don't really know the best way to implement it. Below is my latest attempt:
import React, { useState, useEffect } from 'react';
const App = () => {
const URL = 'http://api.com';
const [data, setData] = useState({});
useEffect(() => {
const resp = fetch(URL).then(res => {
console.log(res)
});
});
return (
<div>
// display content here
</div>
)
}
You could create a custom hook called useFetch
that will implement the useEffect
hook.
By passing an empty array as the second argument to the useEffect
hook will trigger the request on componentDidMount
.
Here is a demo in code sandbox.
See code below.
import React, { useState, useEffect } from 'react';
const useFetch = (url) => {
const [data, setData] = useState(null);
// empty array as second argument equivalent to componentDidMount
useEffect(() => {
async function fetchData() {
const response = await fetch(url);
const json = await response.json();
setData(json);
}
fetchData();
}, [url]);
return data;
};
const App = () => {
const URL = 'http://www.example.json';
const result = useFetch(URL);
return (
<div>
{JSON.stringify(result)}
</div>
);
}
这篇关于React Hooks - 发出 Ajax 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!