【发布时间】:2020-11-10 13:46:55
【问题描述】:
我正在 React 中创建一个自定义钩子,用于从 GitHub 作业 API 获取作业。但是CORS会产生问题。所以我也使用const BASE_URL = 'https://cors-anywhere.herokuapp.com/https://jobs.github.com/positions.json';
此抛出错误 429(请求过多)。我不使用任何后端。
这个钩子会在加载应用程序时从 app.js 调用一次。
useFetchJobs.js
import { useReducer, useEffect } from 'react';
import axios from 'axios';
const ACTIONS = {
MAKE_REQUEST: 'make-request',
GET_DATA: 'get-data',
ERROR: 'error'
}
const BASE_URL = 'https://jobs.github.com/positions.json';
function reducer(state, action) {
switch (action.type) {
case ACTIONS.MAKE_REQUEST:
return { jobs: [], loading: true }
case ACTIONS.GET_DATA:
return { ...state, jobs: action.payload.jobs, loading: false }
case ACTIONS.ERROR:
return { ...state, jobs: [], loading: false , error: action.payload.error }
default:
return state;
}
}
export default function useFetchJobs(params, page) {
const [state, dispatch] = useReducer(reducer, { jobs: [], loading: true });
useEffect(() => {
dispatch({ type: ACTIONS.MAKE_REQUEST });
axios.get(BASE_URL, {
params: { markdown: true, page: page, ...params }
}).then(res => {
dispatch({ type: ACTIONS.GET_DATA, payload: { jobs: res.data }});
}).catch(e => {
dispatch({ type: ACTIONS.ERROR, payload: { error: e }});
})
}, [params, page]);
return state;
};
App.js
import React from 'react';
import useFetchJobs from "./useFetchJobs";
import Container from "react-bootstrap/Container";
const App = () => {
const { jobs, loading, error } = useFetchJobs();
return (
<Container>
{loading && <h1>Loading...</h1>}
{error && <h1>Error. Please try again...</h1>}
<h1>{jobs.length}</h1>
</Container>
);
}
export default App;
【问题讨论】:
-
这能回答你的问题吗? React - Axios call make too many requests
-
不,在传递空数组后得到 429 (Too Many Requests)
-
可能每次渲染时参数或页面都会发生变化,这使得 useEffect 方法再次运行并导致无限循环。
-
如果我传递空参数或页面也会出现此错误 429
-
您的 UseEffect 似乎在“监听”参数和页面状态。如果您使用这些,请尝试收听 setParams 和 setPage。与纯状态相比,何时调用这些更容易控制
标签: javascript reactjs http axios http-status-code-429