json - 独特的“关键”道具。警告但我有钥匙
问题描述
我的控制台出现错误,
我的 JSON 在这里https://dev.justinblayney.com/wp-content/uploads/2020/12/main-menu.json_.zip
警告:列表中的每个孩子都应该有一个唯一的“关键”道具。
我的页面上显示的是(所以它们都是独一无二的,所以 WTF 反应)
密钥:2429 密钥:2430 密钥:3859 密钥:2421 密钥:2802 密钥:2428
附带说明一下,我发现使用函数是获取 JSON 文件的一种糟糕方法,我还会收到内存泄漏警告,而且我在网上看到的每个教程都使用类或 axios
检查MyRoutes
. 有关更多信息,请参阅https://reactjs.org/link/warning-keys。MyRoutes@http://localhost:3000/react-wordpress-headless/static/js/main.chunk.js:63:81 div Router@http://localhost:3000/react-wordpress-headless/static/js/ 0.chunk.js:35747:30 BrowserRouter@http://localhost:3000/react-wordpress-headless/static/js/0.chunk.js:35367:35 App@http://localhost:3000/react- wordpress-headless/static/js/main.chunk.js:94:1
function MyRoutes() {
const [myrt, setMyrt] = useState([]);
useEffect(() => {
fetch("main-menu.json" ,{
headers : {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
.then(res => res.json())
.then(json =>{
setMyrt(json.items)}
)
});
return (
<>
{Object.keys(myrt).map((ky, idx)=> (
<>
<h2>KEY: {myrt[ky].ID} </h2>
<Route exact path={`/${myrt[ky].slug}`} component={Page} key={myrt[ky].ID} /></>
))}
</>
);
}
解决方案
key
prop 应该在第一个元素上定义,在你的情况下它是React.Fragment
.
function MyRoutes() {
const [myrt, setMyrt] = useState([]);
useEffect(() => {
fetch('main-menu.json', {
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
})
.then((res) => res.json())
.then((json) => {
setMyrt(json.items);
});
});
return (
<>
{Object.keys(myrt).map((ky, idx) => (
<React.Fragment key={ky}>
// ------------^
<h2>KEY: {myrt[ky].ID} </h2>
<Route exact path={`/${myrt[ky].slug}`} component={Page} key={myrt[ky].ID} />
</React.Fragment>
))}
</>
);
}
推荐阅读
- r - R:具有多层次组织的 ICC(心理)功能
- reactjs - 如何在样式组件中插入 CSS 属性?
- javascript - 初学者 - 路由功能中的查询发生了什么?
- oracle - ORA-04091 表 * 正在变异,触发器/函数可能看不到它
- java - 将大型 build.gradle 拆分为多个文件
- node.js - 在节点 Alpine 环境中,使用 LibreOffice 执行 pdf 转换会破坏除特殊字符和数字之外的所有内容
- spring - 当我们为所有人使用存储库保存方法时,使用 PATCH、POST、PUT 类型有什么意义?
- thymeleaf - 如何将 authority.getAuthority() 的答案与 thymeleaf 中的特定角色“ROLE_ADMIN”进行比较?
- html - 为什么默认无法获得font awesome 4.7 版本图标?
- powershell - 之前运行的 xcopy 命令现在在 power shell 中不起作用