[英]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.