dispatch 写在函数组件外面报错
来源:13-15 -点击组件库中的组件,添加到画布中

weixin_慕少7054963
2024-07-27
[eslint]
src\pages\question\Edit\ComponentLib.tsx
Line 13:20: React Hook "useDispatch" is called in function "genComponent" that is neither a React function component nor a custom React Hook function. React component names must start with an uppercase letter. React Hook names must start with the word "use" react-hooks/rules-of-hooks
Line 15:23: React Hook "useCallback" is called in function "genComponent" that is neither a React function component nor a custom React Hook function. React component names must start with an uppercase letter. React Hook names must start with the word "use" react-hooks/rules-of-hooks
Search for the keywords to learn more about each error.
这个 错误是因为eslint 配置问题还是改版了?
以下是代码为拷贝老师的
import React, { FC, useCallback } from 'react'
import { nanoid } from 'nanoid'
import { Typography } from 'antd'
import { useDispatch } from 'react-redux'
import { componentConfGroup, ComponentConfType } from '../../../components/QuestionComponents'
import { addComponent } from '../../../store/componentsReducer'
import styles from './ComponentLib.module.scss'
const { Title } = Typography
function genComponent(c: ComponentConfType) {
const { title, type, Component, defaultProps } = c
const dispatch = useDispatch()
const handleClick = useCallback(() => {
dispatch(
addComponent({
fe_id: nanoid(), // 前端生成的 id
title,
type,
props: defaultProps,
})
)
}, [])
return (
<div key={type} className={styles.wrapper} onClick={handleClick}>
<div className={styles.component}>
<Component />
</div>
</div>
)
}
const Lib: FC = () => {
return (
<>
{componentConfGroup.map((group, index) => {
const { groupId, groupName, components } = group
return (
<div key={groupId}>
<Title level={3} style={{ fontSize: '16px', marginTop: index > 0 ? '20px' : '0' }}>
{groupName}
</Title>
<div>{components.map(c => genComponent(c))}</div>
</div>
)
})}
</>
)
}
export default Lib
写回答
1回答
-
报错的意思是:hook 只能在组件或者另一个hook中调用。
你可以把两个 hook 的调用,移到 FC 函数内部
022024-10-07
相似问题
服务器组件的区别
回答 1
为什么我用useDispatch会报错
回答 2