Javascript “反应钩”;“用户教育者”;在函数“中调用”;“获取数据”;它既不是React函数组件,也不是自定义React钩子函数
我试图使用fetchData钩子中的fetchData,但奇怪的是,它会产生以下错误->Javascript “反应钩”;“用户教育者”;在函数“中调用”;“获取数据”;它既不是React函数组件,也不是自定义React钩子函数,javascript,reactjs,Javascript,Reactjs,我试图使用fetchData钩子中的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 2
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文件代码->
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
从“React”导入React
从“react bootstrap”导入{Container}
从“./fetchData”导入fetchData
函数App(){
const{jobs,loading,error}=fetchData(null,1)
返回(
{jobs.length}
{加载和加载(&L)}
{error&&error}
)
}
导出默认应用程序
您需要调用函数useFetchData
或类似的函数,根据React规范,use…
是有效的钩子名
这被描述为:
它的名字应该总是以use开头,这样你一眼就能看出hook的规则适用于它
以及:
它假定以“use”开头的任何函数以及紧跟其后的大写字母都是钩子
您需要调用函数
useFetchData
或类似的函数,根据React规范,use…
是有效的钩子名
这被描述为:
它的名字应该总是以use开头,这样你一眼就能看出hook的规则适用于它
以及:
它假定以“use”开头的任何函数以及紧跟其后的大写字母都是钩子
自定义挂钩应以关键字
use
根据。自定义挂钩应以关键字
use
根据。尝试将
fetchData
重命名为useetchdata
?尝试将fetchData
重命名为useetchdata
?