![](/img/trans.png)
[英]React Hook is called in function “onSubmit” which is neither a React function component or a custom React Hook function
[英]React Hook “useReducer” is called in function “fetchData” which is neither a React function component or a custom React Hook function
我正在尝试使用 fetchData 钩子中的获取数据,但奇怪的是它会产生以下错误->
Line 26:31: React Hook "useReducer" is called in function "fetchData" which is neither a React function component or a custom React Hook function react-hooks/rules-of-hooks
Line 28:5: React Hook "useEffect" is called in function "fetchData" which is neither a React function component or a custom React Hook function react-hooks/rules-of-hooks
我的 fetchData.js 文件代码->
import { useReducer, useEffect } from "react"
import axios from 'axios'
const ACTION = {
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 ACTION.MAKE_REQUEST:
return { loading: true, jobs: [] }
case ACTION.GET_DATA:
return { ...state, loading: false, jobs: action.payload.jobs }
case ACTION.ERROR:
return { ...state, loading: false, error: action.payload.error, jobs: [] }
default:
return state
}
}
function fetchData(params, page) {
const [state, dispatch] = useReducer(reducer, { jobs: [], loading: true, error: false })
useEffect(() => {
dispatch(ACTION.MAKE_REQUEST)
axios.get(BASE_URL, {
params: { markdown: true, page: page, ...params }
}).then(res => {
dispatch({ type: ACTION.GET_DATA, payload: { jobs: res.data } })
}).catch(e => {
dispatch({ type: ACTION.ERROR, payload: { error: true } })
})
}, [params, page])
return state
}
export default fetchData
我的 app.js 文件很简单。 只需从 fetchData 挂钩中获取 api 数据并对其进行解构。 然后在返回中渲染它->
import React from 'react'
import { Container } from 'react-bootstrap'
import fetchData from './fetchData'
function App() {
const { jobs, loading, error } = fetchData(null, 1)
return (
<Container>
<div>{jobs.length}</div>
{loading && <h1>loading</h1>}
{error && <h1>error</h1>}
</Container>
)
}
export default App
自定义钩子应按照https://reactjs.org/docs/hooks-rules.html的关键字use
开头。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.