1 回答

TA貢獻1836條經驗 獲得超5個贊
提供給 useEffect 的回調必須返回一個函數或未定義(如果提供了一個函數,則這被認為是一個清理函數。清理函數用于分離事件偵聽器,取消任何正在進行的請求,并防止如果組件被卸載則進行任何更新)
為了訪問您的http請求產生的響應,您應該將其存儲在一個狀態中(您可以使用useState或useReducer)
const [rest, setResp] = React.useState();
React.useEffect(() => {
wait().then(_ => getData()).then(setResp);
}, [YOUR_DEPENDENCIES]);
// update jsx based on rest
根據您問題中的更新,您需要的是輪詢
請查看下面的示例(請記住,這是說明可能的解決方案的代碼)
function usePolling(fetcher, interval) {
const [payload, setPayload] = React.useState(null);
React.useEffect(function () {
// you must implement the error handling
fetcher()
.then(function (resp) {
setPayload(resp)
})
}, [fetcher]);
React.useEffect(function () {
let timeoutId;
function poll() {
timeoutId = setTimeout(function () {
// you must implement the error handling
fetcher()
.then(function (resp) {
setPayload(resp)
poll();
})
}, interval);
}
poll()
return function () {
clearTimeout(timeoutId);
}
}, [fetcher, interval]);
return payload;
}
function App() {
const payload = usePolling(function () {
return Promise.resolve(Date.now())
}, 3000);
return (
<div>polling payload: {payload}</div>
)
}
ReactDOM.render(<App/>, document.getElementById('app'))
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
</head>
<body>
<div id="app"></div>
</body>
</html>
添加回答
舉報