繁体   English   中英

在不存在的行反应 ESLint 错误

[英]React ESLint error at line that doesn't exist

我正在使用 nextjs,当我运行next build时它失败并给出以下错误。 该错误将我指向第 19 行(空行)和第 33 行(甚至不存在?)。

对于错误消息本身,我看到了eslint-plugin-react的一个问题,据说最近已经修复了,但我仍然在package-lock.json的最新更新版本中遇到错误:

"eslint-plugin-react": ">=7.29.4",

我也试过删除.next文件夹并再次进行next build ,删除node-modules并进行npm install ,错误仍然发生。

有错误的文件:

import Subtitle1 from './subtitle-1'
import Subtitle2 from './subtitle-2'

class SwitchSubtitle extends Component {
    constructor(...args) {
      super(...args);
      this.state = {
        stitles: [<Subtitle1/>, <Subtitle2/>],
        index: 0
      };
    }
  
    componentDidMount() {
      this.timer = setInterval(() => {
        this.setState({index: this.state.index + 1})
      }, 3500)
    }
  
    render() {
      const { index, stitles } = this.state;
      return(
          <p>{stitles[index % 2]}</p>
      );
    }
}

export default SwitchSubtitle

next build给出的错误:

info  - Checking validity of types

Failed to compile.

./components/landing/switchSubtitle.js
9:19  Error: Missing "key" prop for element in array  react/jsx-key
9:33  Error: Missing "key" prop for element in array  react/jsx-key

当您呈现组件数组时,每个元素都需要一个在数组中唯一的key

您在这里有效地渲染了这样一个数组:

stitles: [<Subtitle1/>, <Subtitle2/>]

您可以添加密钥,如下所示:

stitles: [<Subtitle1 key=“1”/>, <Subtitle2 key=“2”/>]

但我认为更好的方法是将组件本身放入数组中并推迟渲染,直到需要时再渲染。 这样你只渲染实际显示的组件:

stitles: [Subtitle1, Subtitle2]

// …

const Cmp = stitles[index % 2];

return (
   …
   <Cmp />
   …
)

我认为在这种情况下,错误有点误导,它可能意味着您只需要简单地向该组件传递一个密钥(假设您映射它)

尝试将键添加到 p 元素

  return(
      <p key={index}>{stitles[index % 2]}</p>
  );

我不认为你需要数组 stitles 作为 state,索引正在递增和 state 被更改以及渲染 function 被触发的事实就足够了,你为什么不试试这个:

return(
   {index%2 == 0 ? (
     ....
     <Subtitle1/>
     ...
   ) : (
     ...
     <Subtitle2/>
     ...
   )}
);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM