首页 > 解决方案 > 独特的“关键”道具。警告但我有钥匙

问题描述

我的控制台出现错误,

我的 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}  /></>
            ))} 
        </>
  
    );
}

标签: jsonreactjs

解决方案


keyprop 应该在第一个元素上定义,在你的情况下它是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>
      ))}
    </>
  );
}

推荐阅读