javascript – React Hooks – 发出Ajax请求
作者:互联网
我刚刚开始使用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 => {
console.log(res)
});
});
return (
<div>
// display content here
</div>
)
}
解决方法:
您可以创建一个名为useFetch的自定义钩子来实现useEffect钩子.
通过将空数组作为第二个参数传递给useEffect钩子,将触发componentDidMount上的请求.
Here is a demo in code sandbox.
见下面的代码.
import React, { useState, useEffect } from 'react';
const useFetch = (url) => {
const [data, updateData] = useState(undefined);
// empty array as second argument equivalent to componentDidMount
useEffect(() => {
async function fetchData() {
const response = await fetch(url);
const json = await response.json();
updateData(json);
}
fetchData();
}, [url]);
return data;
};
const App = () => {
const URL = 'http://www.example.json';
const result = useFetch(URL);
return (
<div>
{JSON.stringify(result)}
</div>
);
}
标签:javascript,reactjs,react-hooks 来源: https://codeday.me/bug/20191005/1854686.html