【问题标题】:Why do i get : Must use destructuring state assignment? [duplicate]为什么我得到:必须使用解构状态分配? [复制]
【发布时间】:2026-02-22 15:25:01
【问题描述】:

在我的反应组件中,我有一个构造函数:

  constructor() {
    super();
    this.state = { rows: [{ prior_year: 1000, current_year: 2000 }] };
  }

在我的渲染中我有:

  <Table>
    {this.state.rows.map(row => (
      <Tr>
        <Td>{row.prior_year}</Td>
        <Td>{row.current_year}</Td>
      </Tr>
    ))}

    <Button onClick={() => this.handleAddAdjustment()} label="Add another adjustment" />
  </Table>

为什么我会收到此 lint 错误:必须使用解构状态分配?

【问题讨论】:

    标签: javascript reactjs eslint


    【解决方案1】:

    这只是一个 linter,它告诉您将 this.state.rowsconst { rows } = this.state ; 之类的东西一起使用。这意味着每当你想使用一个对象属性时,你首先要对其进行解构,然后再使用它。

    例如,这是另一个示例,主要用于功能性反应组件。

    const MyFunctionalReactComponent = ({id}) => {
      return (<div id={id} />)
    };
    

    你也可以写成

    const MyFunctionalReactComponent = (props) => {
      return (<div id={props.id} />)
    };
    

    查看这里了解更多详情,https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/destructuring-assignment.md

    原因:这是一种非常简洁的编码方式,因为您将在一行中解构所有变量,并避免每次使用新状态变量时this.state

    【讨论】: