【问题标题】:Unused state fields in react eslint error反应 eslint 错误中未使用的状态字段
【发布时间】:2021-11-09 06:00:40
【问题描述】:

新的反应,我正在使用一个类组件并得到 filteredItems 的未使用状态字段错误

不明白为什么当我已经在我的数据表组件中使用它们时它没有被使用

  constructor(props) {
    super(props);
    this.state = {
      filterText: '',
      filteredItems: '', //Initalize state
    };
  }

 // ... ommitted other parts

  render() {
    const result = arr1.map(item => item[1]);
    // this.filteredItems = result;
    if (result) {
      this.setState({
        filteredItems: result,  //Trying to setState with result array. Getting unused state fields error
      });
    }

    return (
      <React.Fragment>
        <DataTable
          columns={columns}
          data={this.filteredItems} // Trying to Using this.filteredItems

    // ... ommitted other parts

【问题讨论】:

  • this.filteredItems 不指向您的状态值。应该改成this.state.filteredItems
  • 我现在收到了 >> 超过了最大更新深度。当组件在 componentWillUpdate 或 componentDidUpdate 中重复调用 setState 时,可能会发生这种情况。 React 限制了嵌套更新的数量以防止无限循环。
  • 这是由于 setStaterender 方法中被调用。您可以将arr1.map(item =&gt; item[1]) 行直接移动到DataTabledata 属性中作为快速修复(同时删除setState 调用)。

标签: reactjs jsx eslint


【解决方案1】:

错误的意思正是它所说的:您的状态有字段[s] 没有读取任何地方。 如果您初始化 state={ attributeA: '', attributeB: ''} 并且从未读取过 attributeA,那么您将收到该错误。

您的示例有很多缺失的代码。但是,在您的示例中,您没有使用 state.filterText,这就是错误的来源。

请记住,您收到的错误不是来自 javascsript 或 React 本身,而是来自 eslint,它是一种用于突出错误做法的工具(例如声明状态属性而不使用它们)。

【讨论】:

    猜你喜欢
    • 2018-08-02
    • 2021-07-19
    • 2022-12-03
    • 2020-04-08
    • 2020-10-14
    • 2017-11-20
    • 2021-05-03
    • 1970-01-01
    • 2020-08-30
    相关资源
    最近更新 更多