IT이야기

ESLint: 구성 요소 정의에 displayName이 누락됨(react/display-name)

cyworld 2022. 3. 13. 10:30
반응형

ESLint: 구성 요소 정의에 displayName이 누락됨(react/display-name)

나는 antd가 있는 리액션 후크 부품을 사용하고 있다.테이블의 열을 설정할 때 렌더 함수는 ESLint 오류를 제공하는 것이다.

ESLint: 구성 요소 정의에 displayName이 누락됨(react/display-name)

객체에 displayName을(를) 추가해 보았지만 이 기능이 작동하지 않는다.

오류는 다음과 같이 나타난다.

암호는 다음과 같다.

const columns_payment_summary_table = [ 
    {
      title: FooConstants.LABEL_QUANTITY_SELECTED,
      dataIndex: 'group',
      key: 'group',
      render: text => (
        <span>{getCountForCountry(text)}</span>
      ),
    }
  ]

누구 도와줄 사람 있어?

다음은 전체 구성 요소 코드(관련 비트만)

import * as FooConstants from './constants'
import {connect} from 'react-redux'
import React, {useState, useEffect} from 'react'
import {Card, Table} from 'antd'
import PropTypes from 'prop-types'

const propTypes = {
  foos: PropTypes.object.isRequired,
}

function Foos(props) {

  const [selectedFooRows, setSelectedFooRows] = useState([])

  useEffect(() => {
    getFooDetails()
  }, [])

  function getFooDetails() {
    props.dispatch({
      type: FooConstants.GET_FOO_PAYMENT_SUMMARIES,
      params: {
        'group_by': 'country_code',
        'type': FooConstants.CLAIM_FOO,
      }
    })
    props.dispatch({
      type: FooConstants.GET_FOO_PAYMENTS,
      params: {'type': FooConstants.CLAIM_FOO, }
    })
  }

  const columns_payment_summary_table = [
    {
      title: FooConstants.LABEL_QUANTITY_SELECTED,
      dataIndex: 'group',
      key: 'group',
      render: text => (
        <span>{getCountForCountry(text)}</span>
      ),
    }
  ]

  function getCountForCountry(country_code){
    let selected_country = selectedFooRows.filter(function(row){
      return row.group === country_code
    })

    if(selected_country && selected_country.length > 0){
      return selected_country[0].ids.length
    } else {
      return 0
    }
  }

  return (
    <div>
      <Card
        title={FooConstants.LABEL_FOO_SUMMARY}>
        <Table
          columns={columns_payment_summary_table}
          bordered={true}
          dataSource={props.foos.foo_payment_summaries}
          loading={props.foos.foo_payment_summaries_pending && !props.foos.foo_payment_summaries}
          rowKey={record => record.group}
        />
      </Card>
    </div>
  )
}

Foos.propTypes = propTypes

const mapStateToProps = (state) => {
  return {foos: state.foosReducer}
}

export default connect(
  mapStateToProps,
)(Foos)

ESLint는 새로운 구성요소에 이름을 지정하지 않고 새로운 구성요소를 정의하고 있다고 생각한다.

이는 ESLint가 렌더 프로펠러 패턴을 인식할 수 없기 때문에, 이 렌더 프로펠러를 구성요소에 직접 쓰는 것이 아니라 객체에 쓰는 것이기 때문에 설명된다.

당신은 그것을 넣을 수 있다.render의 jsx 구현에 직접 지원하다.<Column>구성 요소 또는 ESLint의 오류를 종료하는 방법:

const columns_payment_summary_table = [ 
    {
        title: SettlementConstants.LABEL_QUANTITY_SELECTED,
        dataIndex: 'group',
        key: 'group',
        // eslint-disable-next-line react/display-name
        render: text => (
            <span>{getCountForCountry(text)}</span>
        ),
    }
]

도움이 되었으면 좋겠다;)

에 대해 일반 기능 사용render키는 또한 경고를 비활성화할 필요 없이 ESLint 경고를 제거한다.

const columns_payment_summary_table = [ 
    {
        title: SettlementConstants.LABEL_QUANTITY_SELECTED,
        dataIndex: 'group',
        key: 'group',
        render: function countForCountry(text) {
            return <span>{getCountForCountry(text)}</span>
        },
    }
]

모든 파일에서 이 문제를 방지해야 하는 경우 아래를 의 규칙 섹션에 추가하십시오..eslintrc.js파일

{
  ...
  "rules": {
    "react/display-name": "off"
  }
}

때로는 한두 군데에서만 오류가 발생하면 규칙을 우회할 수 있다.여러 곳에 동일한 사용 사례가 있으면 어떻게 하시겠습니까?매번 우리는 규칙을 비활성화해야 한다.

대신 렌더링 속성에 함수를 할당하여 이 오류를 우회할 수 있다.

const getMyHTML = (text) => <span>{getCountForCountry(text)}</span>

const columns_payment_summary_table = [
  {
    title: SettlementConstants.LABEL_QUANTITY_SELECTED,
    dataIndex: 'group',
    key: 'group',
    render: getMyHTML,
  }
]

이것은 ESLint 이슈에서 상당히 철저하게 다루어져 있다.

Loïc제안한 것처럼 보푸라기의 오류를 억제하는 것이 여기서는 가장 간단한 선택이다.

그러나 보푸라기 오류는 디버깅, 특히 React DevTools' Component 뷰에서 유용하게 사용될 수 있다.기능을 할당하는 가장 쉬운 방법 adisplayName명명된 함수 선언을 사용하고 정의를 실행하십시오.

function renderTable(text) {
  return (<span>{getCountForCountry(text)}</span>);
}
const columns_payment_summary_table = [
  {
    title: SettlementConstants.LABEL_QUANTITY_SELECTED,
    dataIndex: 'group',
    key: 'group',
    render: text => (
      <span>{getCountForCountry(text)}</span>
    ),
  }
]

하지만 그것은 분명히 더 장황한 것이고, 만약 여러분이 DevTools에서 이름으로 렌더링된 구성요소를 찾을 필요가 없다고 예상한다면, 오류를 억제하는 것이 가장 간단하다.

익명 기능과 화살표 기능을 사용하면ESLint: Component definition is missing displayName (react/display-name)나오는 이유는 우리가 기능을 통해 부품을 렌더링할 때 렌더링 기능도 이름을 붙여 displayName을 부여하기 때문이다.

하지만 정상 기능을 사용하는 것만으로는 충분하지 않을 수도 있지만, 다음과 같은 경고를 받을 수도 있다.

Warning: Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it.

정상적인 기능은 렌더링 후 바로 실행해야 한다.나는 다음 코드를 사용하여 두 가지 규칙을 통과시켰다.

render: () => {
    return (function Actions() {
        return (
            <Button>
            View
            </Button>
                );
            })();
        },

참조URL: https://stackoverflow.com/questions/55620562/eslint-component-definition-is-missing-displayname-react-display-name

반응형