簡體   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