【问题标题】:Give unique key props to react nested map提供独特的关键道具来反应嵌套地图
【发布时间】:2022-07-14 00:47:51
【问题描述】:

如何在反应映射中赋予唯一的关键道具。我使用 uuidv4 库,但 react 还说每个子组件都应该有一个唯一的 key prop。 这是我使用 uuidv4 npm 库的代码。

我尝试了很多方法,但都不起作用。

    // import Sidebar from '../components/Sidebar'
  import React from 'react'
  import Navbar from '../components/Navbar';
  import ButtonGroup from '../components/ButtonGroup';
  import MCQS from '../components/MCQ';
  import { Outlet } from 'react-router';
  import { v4 as uuidv4 } from 'uuid';
  import { useSelector } from 'react-redux';
  const C_P_HOME = () => {
    const { heading } = useSelector(state => state.heading);
    const { questions } = useSelector(state => state.question);
    return (
      <>
        <Navbar isContainerTrue={false} />
        <div className='grid grid-cols-12 '>
          <div className="col-span-6 bg-slate-100 grid grid-cols-12 p-8 h-screen items-baseline">
            <ButtonGroup />
            <Outlet />
          </div>
          <div className="col-span-6 bg-slate-200 h-screen overflow-y-scroll">
            <div className="heading select-none">
              <h1 className='text-2xl text-center font-bold mt-8'>{heading}</h1>
            </div>
            <div className="questions p-8">

              {
                questions.map((q, index) => {
                  return (
                    <>
                      <h2 className='text-2xl font-semibold' key={uuidv4()}>Q:{(index + 1) + " " + q.heading}</h2>
                      <ol className='list-[lower-roman]' key={uuidv4()}>
                        {
                          q.questions.map((ques, index) => {
                            return (
                              <>
                                <li className='text-lg ml-16' key={uuidv4()}>{ques}</li>
                              </>
                            )
                          })
                        }
                      </ol>
                    </>
                  )
                })
              }
            </div>
          </div>

        </div>
      </>
    )
  }

  export default C_P_HOME;

这是我的错误截图。

【问题讨论】:

    标签: javascript reactjs arrays


    【解决方案1】:

    通常循环遍历数组等时的键来自数组本身中的每个项目。假设你的question 有一个id,你想用那个id 作为key。由于 id 通常是唯一的,因此除非它是 f.ex,否则该项目的此密钥不会更改。删除

    【讨论】:

      猜你喜欢
      • 2016-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-31
      • 1970-01-01
      • 2018-09-28
      • 2017-09-23
      • 1970-01-01
      相关资源
      最近更新 更多