升级React与Next.js后出现fetchPriority警告,求非金丝雀版本解决办法
fetchPriority属性警告问题 问题描述
升级React和Next.js到最新版本后,控制台出现以下警告:
Warning: React does not recognize the
fetchPriorityprop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as lowercasefetchpriorityinstead. If you accidentally passed it from a parent component, remove it from the DOM element.
at img
at eval (webpack-internal:///./node_modules/next/dist/client/image-component.js:136:11)
at eval (webpack-internal:///./node_modules/next/dist/client/image-component.js:245:47)
at a
at LinkComponent (webpack-internal:///./node_modules/next/dist/client/link.js:110:19)
查阅官方相关Issue后,仅给出安装金丝雀版本的解决方案,但不愿在生产环境使用该版本,寻求替代解决方法。
可行解决方案
1. 封装自定义Image组件过滤属性
封装Next.js的Image组件,手动剔除fetchPriority属性,避免其传递到底层DOM元素:
import NextImage from 'next/image'; const Image = (props) => { // 解构移除fetchPriority属性 const { fetchPriority, ...restProps } = props; return <NextImage {...restProps} />; }; export default Image;
之后项目中统一使用这个自定义Image组件替代原生Next.js Image即可。
2. 降级到无该问题的稳定版本
查找fetchPriority属性问题出现前的最后一个稳定Next.js版本(比如v13.4.19),执行降级命令:
# npm 降级 npm install next@13.4.19 # yarn 降级 yarn add next@13.4.19
降级前建议确认该版本与项目中其他依赖的兼容性。
3. 配置ESLint规则拦截属性传递
通过ESLint规则限制向Image组件传递fetchPriority属性,从源头避免警告:
在项目的.eslintrc.json中添加规则:
{ "rules": { // 忽略小写fetchpriority属性的警告(若有需要) "react/no-unknown-property": ["error", { "ignore": ["fetchpriority"] }], // 自定义规则禁止向Image组件传递fetchPriority "no-restricted-properties": [ "error", { "object": "Image", "property": "fetchPriority", "message": "请勿向Next.js Image组件传递fetchPriority属性,避免触发React警告" } ] } }
内容的提问来源于stack exchange,提问作者Botanico-Hub

