[英]How to use a bootstrap load spinner while fetching data from an external api?
While fetching information from a url takes a long time, how can I utilize the bootstrap load spinner to hide the delay and make the website looks more interactive?虽然从 url 获取信息需要很长时间,但我如何利用引导加载微调器来隐藏延迟并使网站看起来更具交互性?
I prefer to have a single state that stores all the information about the request ie it's status
, data
& error
.我更喜欢有一个 state 来存储有关请求的所有信息,即它的
status
、 data
和error
。
Based on the status
field you have render the appropriate UI (like loading spinner, error screen).根据
status
字段,您呈现了适当的 UI(如加载微调器、错误屏幕)。
I have used the state hook in the example below, you can also use the reducer hook if you prefer.我在下面的示例中使用了 state 钩子,如果您愿意,也可以使用 reducer 钩子。
function App(props) { const [{ status, data, error }, setState] = React.useState({ status: "PENDING", data: null, error: null }); React.useEffect(() => { let isCancelled = false; setState({ status: "PENDING", data: null, error: null }); fetch("https://jsonplaceholder.typicode.com/todos/1").then(res => res.json()).then(data => { if (isCancelled) { return; } setState({ status: "RESOLVED", data, error: null }); }).catch((error) => setState({ status: "REJECTED", error, data: null })); return () => { isCancelled = true; }; }, []); if (status === "PENDING") { return <p>Loading...</p>; } else if (status === "REJECTED") { return <pre>{JSON.stringify(error)}</pre>; } else { return <pre>{JSON.stringify(data)}</pre>; } } const root = ReactDOM.createRoot(document.getElementById("root")); root.render( <React.StrictMode> <App /> </React.StrictMode> );
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script> <div id="root"></div>
const [loading, setLoading] = useState(false)
useEffect(() => {
setLoading(true)
// Do your Fetch and stuff
setLoading(false)
}, []) }, [])
There ya go有你 go
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.