为什么我得到:必须使用解构状态分配?

时间:2019-03-21 04:20:32

标签: javascript reactjs eslint

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

  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>

为什么会出现此皮棉错误:必须使用解构状态分配?

1 个答案:

答案 0 :(得分:0)

这只是一个小故事,它告诉您将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

相关问题