简体   繁体   English

React 错误:渲染的钩子比上一次渲染时更多。 当使用 useState 和 map

[英]React Error: Rendered more hooks than during the previous render. when using useState and map

I have React code which fetch from my Api posts and displays it.我有从我的 Api 帖子中获取并显示的 React 代码。

when I tried to display the posts with map , I used useState inside the map and I got this error:当我尝试使用map显示帖子时,我在useState中使用了map ,我收到了这个错误:

Error: Rendered more hooks than during the previous render.

When I deleted the useState it worked.当我删除 useState 时,它起作用了。

This is my code这是我的代码

import {useState,useContext,useEffect} from "react"
import {username} from "./username"

const PostDisplay = (post) => {

  const [try, setTry] = useState("")

  return (
    <div>Hello</div>
  );


}


function Home(){

    const [loggedIn,setLoggedIn] = useContext(username)

    const [posts, setPosts] = useState([])

    useEffect(() => {
      fetch("/posts")
      .then((response) => response.json())
      .then((data) => {
      setPosts(data)
      console.log(data)
      })   
    }, [])

      

if(loggedIn){
    return (
    <div align="center">
      <br/>
      <br/>
      <div>
      {posts.map(PostDisplay)}
      </div>
    </div>
    )
}

else{
    return (
        <div>
          <h1 align="center">You are not logged in!</h1>
        </div>
        )
}

}

export default Home

please help me.请帮我。

You cannot assign a React component like that inside a map您不能在 map 中分配像这样的 React 组件

{posts.map((post) => <PostDisplay post={post}/>)}

iterate through the array and pass the value as prop to the component.遍历数组并将值作为 prop 传递给组件。

const PostDisplay = ({post}) => {

  const [try, setTry] = useState("")

  return (
    <div>Hello </div>
  );


}

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

相关问题 渲染的钩子比上一个渲染期间要多。 使用React Hooks发布表单数据时 - Rendered more hooks than during the previous render. when posting form data with React Hooks 比上一次渲染时渲染了更多的钩子。(组件异常) - Rendered more hooks than during the previous render.(component exception) 反应钩子错误:渲染的钩子比上一次渲染时更多 - React hooks error: Rendered more hooks than during the previous render React 中的错误:渲染的钩子比上一次渲染时更多 - Error in React: Rendered more hooks than during the previous render React - 错误:渲染的钩子比上一次渲染时多 - React - Error: Rendered more hooks than during the previous render React Native:渲染的钩子比之前的渲染错误更多 - React Native: Rendered more hooks than during the previous render error React - 获得“比上一次渲染期间渲染的钩子更多”错误 - React - getting “Rendered more hooks than during the previous render” error React Native 错误:渲染的钩子比上一次渲染时更多 - React Native Error: Rendered more hooks than during the previous render React Hooks 渲染了比上一次渲染更多的钩子 - React Hooks Rendered more hooks than during the previous render React/NextJS 使用 UseEffect 错误:渲染的钩子比上一次渲染时更多 - React/NextJS using UseEffect Error: Rendered more hooks than during the previous render
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM