我有一個(gè)功能組件,它從 API 獲取一些數(shù)據(jù)并將其顯示在頁面的某個(gè)位置,問題是發(fā)生錯(cuò)誤時(shí)我想顯示一個(gè)重試按鈕以再次調(diào)用 API。所以我這樣做了:import React, {useEffect, useState} from "react";import api from "../../../api";import {useSnackbar} from "notistack";const ShowPassword = ({uuid}) => { const [password, setPassword] = useState(null); const [retry, setRetry] = useState(false); const {enqueueSnackbar} = useSnackbar(); useEffect(() => { api.showPassword(uuid) .then(res => { setPassword(res.data.password); }) .catch(err => { setRetry(true); enqueueSnackbar('An error occured...', {variant: 'error'}); }) }, [password]); return ( <div> { retry ? <button onClick={() => { setRetry(false); setPassword(null); }} type='button'>Retry</button> : <span>{password ?? 'Loading...'}</span> } </div> );};export default ShowPassword;但是通過單擊“重試”按鈕,它會(huì)顯示,Loading...但不會(huì)再次調(diào)用 API。
在 React JS 中重試 useEffect
慕仙森
2023-01-06 09:48:28