You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React组件props校验缺失报错,请求修复方案

解决React/prop-types报错的方案

你的报错源于ESLint的react/prop-types规则要求:组件接收的所有props必须定义类型验证,而你的Notification组件未给notify和setNotify添加对应的类型校验定义。以下是具体修复步骤:

1. 确保安装prop-types依赖

如果项目尚未安装,执行命令:

npm install prop-types
# 或使用yarn
yarn add prop-types

2. 修改Notification组件代码

导入prop-types包,并为组件添加完整的propTypes定义,明确每个props的类型规则:

import { Snackbar } from '@mui/material'
import React from 'react'
import { Alert } from '@material-ui/lab'
import { makeStyles } from '@material-ui/core'
import PropTypes from 'prop-types' // 新增prop-types导入

const useStyles = makeStyles((theme) => ({
  root: {
    top: theme.spacing(8),
  },
}))

export default function Notification(props) {
  const { notify, setNotify } = props
  const classes = useStyles()

  const handleClose = (event, reason) => {
    setNotify({
      ...notify,
      isOpen: false,
    })
  }

  return (
    <Snackbar
      className={classes.root}
      open={notify.isOpen}
      autoHideDuration={3000}
      anchorOrigin={{ vertical: 'top', horizontal: 'right' }}
      onClose={handleClose}
    >
      <Alert severity={notify.type} onClose={handleClose}>
        {notify.message}
      </Alert>
    </Snackbar>
  )
}

// 新增propTypes类型验证定义
Notification.propTypes = {
  // 定义notify对象的内部结构与类型
  notify: PropTypes.shape({
    isOpen: PropTypes.bool.isRequired,
    type: PropTypes.oneOf(['success', 'error', 'warning', 'info']).isRequired,
    message: PropTypes.string.isRequired,
  }).isRequired,
  // 定义setNotify为函数类型
  setNotify: PropTypes.func.isRequired,
}

3. 修复逻辑说明

  • PropTypes.shape用于校验对象类型props的内部结构,确保notify包含指定属性且类型合法
  • PropTypes.oneOf限制type只能是Alert组件支持的severity枚举值
  • .isRequired标记这些props为必填项,避免组件因缺少依赖props出现异常

完成修改后,ESLint的react/prop-types报错将全部消除。

内容的提问来源于stack exchange,提问作者Darkpsinight

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 01:50:38