请稍等 ...
×

采纳答案成功!

向帮助你的同学说点啥吧!感谢那些助人为乐的人

dispatch 写在函数组件外面报错


[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 函数内部


0 回复 有任何疑惑可以回复我~
  • zac707 #1
    这个怎么移,我也碰到了
    回复 有任何疑惑可以回复我~ 2024-08-18 08:43:47
  • genComponent直接放到函数组件内部,不要放到组件外面
    回复 有任何疑惑可以回复我~ 2024-10-07 20:29:45
问题已解决,确定采纳
还有疑问,暂不采纳
意见反馈 帮助中心 APP下载
官方微信