Jef*_*eyM 6 rest refresh reactjs
我在 ReactJS 中为我的其余 api 创建了一个 fetch hook。我有两个组件。
1) 国家名单
2)添加国家
在组件(2)添加一个国家/地区后,我想告诉组件(1)重新加载数据。我在组件 1 上使用 useEffect 来检索数据。
我试图触发道具上的刷新布尔值。刷新将会触发,但速度会很快。在新数据进入数据库之前,发生了刷新,因此我没有获取新数据。
国家.js
function Countries() {
const [addCountryVisible, setAddCountryVisible] = useState(false);
const countriesApi = useFetch("country/getall");
useEffect(() => {
getCountries();
}, []);
function getCountries() {
countriesApi.run();
}
return ...
}
Run Code Online (Sandbox Code Playgroud)
添加国家/地区.js
function AddCountry(props) {
const [country, setCountry] = useState({
name: "",
flag: ""
});
const addCountryApi = useFetch("country/add", "POST");
const active = props.visible ? "is-active" : null;
const handleSubmit = evt => {
evt.preventDefault();
addCountryApi.run(country, props.setDone);
};
return ...
}
Run Code Online (Sandbox Code Playgroud)
useFetch.js
import { useState } from "react";
import { useAuth0 } from "./react-auth0-wrapper";
const useFetch = (url, method = "GET") => {
const { loading, getTokenSilently } = useAuth0();
const [isLoading, setIsLoading] = useState(false);
const [data, setData] = useState();
const [error, setError] = useState();
const run = async data => {
if (!loading && getTokenSilently) {
setError();
setIsLoading(true);
try {
const token = await getTokenSilently();
const options = {
method,
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`
},
body: JSON.stringify(data)
};
const response = await fetch("/api/" + url, options);
const json = await response.json();
setData(json);
} catch (e) {
setError(e.message);
}
setIsLoading(false);
}
};
return { data, error, isLoading, run };
};
export default useFetch;
Run Code Online (Sandbox Code Playgroud)
我希望在钩子完成添加国家/地区后刷新 useEffect 中的数据以进行更新。
| 归档时间: |
|
| 查看次数: |
5659 次 |
| 最近记录: |