简体   繁体   English

我在反应阵列上使用 map function 时遇到了一些问题

[英]I'm having some problmes using map function over an array in react

I'm reciving an array through props for my component and then store in a state using useEffect.我正在通过我的组件的道具接收一个数组,然后使用 useEffect 存储在 state 中。

const Modules = ({moduleData}) => {

  const [userShowed, setUserShowed] = useState(0);
  const [modules, setModules] = useState([])

  const setUser = (id) => {
    setUserShowed(id);
  }

  useEffect(()=>{
    setModules(Object.values(moduleData).at(userShowed));
  },[moduleData, userShowed])

  return (
    <div>
      <div className="header-container">
        {Object.keys(moduleData).map((element, index) => {
          return <Button clickFunc={() => setUser(index)} btnKey={index} classButton={userShowed === index ? "btn-module is-active":"btn-module"} text={"Module " + (index+1)} />
        })}
      </div>
      <div className="users-container">
        <h4>Number of users in module {userShowed+1}:</h4>
        <div>
          <ul>
            {Object.values(moduleData).at(userShowed).map((element, index) => {
              return <User userKey={index} name={element}/>
            })}
          </ul>
        </div>
      </div>
      <div className="btn-container">
        <Button classButton="btn-users btn-delete" btnKey="delete-btn" text="Delete" icon={<BsFillTrashFill />}/>
        <Button classButton="btn-users btn-advice" btnKey="advice-btn" text="Advice" icon={<IoBulbOutline />} />
        <Button classButton="btn-users btn-create" btnKey="crate-btn" icon={<IoMdAddCircleOutline />} text="Create" iconBefore={true}/>
        <Button classButton="btn-users btn-submit" btnKey="submit-btn" text="Submit" icon={<MdOutlineArrowForwardIos />} />
      </div>
    </div>
  )
}

Then i'm trying to iterate over this array but most of the time a recive this kind of error.然后我试图迭代这个数组,但大多数时候都会收到这种错误。 It's strange because when i take off this map function and i check the component props the array is there(so it's not undefined)这很奇怪,因为当我取下这个 map function 并检查组件道具时,数组在那里(所以它不是未定义的)

This is the error这是错误

Modules.js:34 Uncaught TypeError: Cannot read properties of undefined (reading 'map')
    at Modules (Modules.js:34:1)

photo of the component hook without map没有 map 的组件挂钩的照片

Thanks for the help谢谢您的帮助

Object.values(moduleData).at(index) just returns an item so it is not an array. Object.values(moduleData).at(index) 只返回一个项目,因此它不是数组。 If you want to return and map just moduleData values remove the at()如果要返回 map 只需 moduleData 值删除 at()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM