为了账号安全,请及时绑定邮箱和手机立即绑定

使用 ESLint 响应 PropType

使用 ESLint 响应 PropType

慕娘9325324 2021-10-21 11:02:53
开始使用 ESLint 并遇到了 PropType 的几个问题,目前我有一个道具children,现在假设这个道具是一个string. 我收到一个错误'children' is missing in props validationeslint(react/prop-types),为了解决这个问题,我只是PropTypes像这样使用:CartProvider.propTypes = {  children: PropTypes.string,}以上解决了问题,然后我又遇到了另一个问题 propType "children" is not required, but has no corresponding defaultProps declaration.eslint(react/require-default-props)所以为了解决这个问题,我添加了另一个 PropType 像这样:CartProvider.defaultProps = {  children: PropTypes.string,}所以我的理解是,每次我使用道具时,我都需要使用propTypeand defaultProps。好的,这解决了string基于道具的问题。但实际上这个道具是一个array然后array我得到了其他问题Prop typearray is forbiddeneslint(react/forbid-prop-types)。请帮助我理解为什么 ESLint 将这些道具标记为错误,我知道如何禁用它,但我想了解它为什么会发生,然后编写更好的代码。这是一个示例项目:购物车上下文import React from 'react'import PropTypes from 'prop-types'export const CartContext = React.createContext(null)export const CartProvider = ({ children }) => {  const [cartTotal, setCartTotal] = React.useState(0)  const incrementCartTotal = () => setCartTotal(cartTotal + 1)  return (    <CartContext.Provider      value={{        cartTotal,        incrementCartTotal,      }}    >      {children}    </CartContext.Provider>  )}CartProvider.propTypes = {  children: PropTypes.string,}CartProvider.defaultProps = {  children: PropTypes.string,}应用程序import React from 'react'import { CartContext, CartProvider } from './CartContext'function CartTotalItems() {  const { cartTotal } = React.useContext(CartContext)  return (    <p>      Total items currently in cart:      {cartTotal}    </p>  )}function AddToCart() {  const { incrementCartTotal } = React.useContext(CartContext)  return (    <button type="button" onClick={incrementCartTotal}>      Add to cart    </button>  )}export default function App() {  return (    <CartProvider>      <CartTotalItems />      <AddToCart />    </CartProvider>  )}更新 这对我有用,删除 2 PropTypes 并添加以下内容:CartProvider.propTypes = {  children: PropTypes.node.isRequired,}
查看完整描述

2 回答

?
慕码人2483693

TA贡献1860条经验 获得超9个赞

您误解了 的类型children并混淆了使用defaultProps:


// Use for initial value

CartProvider.defaultProps = {

  counter: 10,


/* 

  You declared the initial value to be the value of `PropTypes.string`

  children: PropTypes.string

*/

}

// Children are always an Array of `ReactElement`/ `ReactElement` node.

CartProvider.propTypes = {

  counter: PropTypes.number,


  children: PropTypes.node.isRequired,


/* Same

  children: PropTypes.oneOfType([

        PropTypes.arrayOf(PropTypes.node),

        PropTypes.node

    ]).isRequired

*/


/*

  props.children can't be a string.

  children: PropTypes.string,

*/

}


查看完整回答
反对 回复 2021-10-21
?
BIG阳

TA贡献1859条经验 获得超6个赞

defaultProps 应该设置一个值而不是再次使用 Proptypes


CartProvider.propTypes = {

  children: PropTypes.string,

}


CartProvider.defaultProps = {

  children: "This is chidlren default string"

}


查看完整回答
反对 回复 2021-10-21
  • 2 回答
  • 0 关注
  • 374 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信