[英]React Hook “useReducer” is called in function “fetchData” which is neither a React function component or a custom React Hook function
i am trying to use the fetch data from fetchData hook but strangely it produces the following errors->我正在尝试使用 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
my fetchData.js files code ->我的 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
my app.js file is simple.我的 app.js 文件很简单。 just fetching the api data from the fetchData hook and destructuring it.
只需从 fetchData 挂钩中获取 api 数据并对其进行解构。 Then rendering it in the return ->
然后在返回中渲染它->
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
You need to call your function useFetchData
or something similar, as per React specs, use...
are valid hook names.你需要调用你的 function
useFetchData
或类似的东西,根据 React 规范, use...
是有效的钩子名称。
This is described here :这在这里描述:
Its name should always start with use so that you can tell at a glance that the rules of Hooks apply to it.
它的名称应该始终以 use 开头,以便您一眼就可以看出 Hooks 的规则适用于它。
It assumes that any function starting with ”use” and a capital letter right after it is a Hook.
它假定任何以“use”开头且紧跟其后的大写字母的 function 都是 Hook。
Custom hooks should start with the keyword use
as per https://reactjs.org/docs/hooks-rules.html .自定义钩子应按照https://reactjs.org/docs/hooks-rules.html的关键字
use
开头。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.