英文:
React component getting rendered multiple times
问题
feedPosts 数组被迭代了 3 次,其中从存储中获取了帖子,尽管我已经为 postComponent 添加了 key 属性,但我仍然收到了添加 key 的错误。
const Home = () => {
const navigate = useNavigate();
const dispatch = useDispatch();
const authToken = Cookies.get("jwtToken");
const feedPosts = useSelector(state => state.feedPosts.posts);
useEffect(() => {
axios.get("http://localhost:8080/posts", {
headers: {
'authorization': authToken
}
}).then((posts) => {
dispatch(setFeedPosts({ posts: posts.data }))
})
}, []);
return (
<div className="homepage">
<div className="post-container">
{feedPosts.map((post) =>
<PostComponent key={post.id}
firstName={post.firstName}
lastName={post.lastName}
userId={post.userId}
content={post.content}
/>
)}
</div>
</div>
)
}
英文:
feedPosts array is getting iterated for 3 times where posts are fetched from the store and though i have added key prop to the postComponent i am getting error to add a key
const Home = ()=>{
const navigate = useNavigate();
const dispatch = useDispatch();
const authToken = Cookies.get("jwtToken");
const feedPosts = useSelector(state => state.feedPosts.posts);
useEffect(()=>{
axios.get("http://localhost:8080/posts",{
headers:{
'authorization': authToken
}}).then((posts)=>{
dispatch(setFeedPosts({posts: posts.data}))
})
},[]);
return(
<div className="homepage">
<div className="post-container">
{feedPosts.map((post)=>
<PostComponent key={post.id}
firstName={post.firstName}
lastName={post.lastName}
userId={post.userId}
content={post.content}
/>
)}
</div>
</div>
)
}
答案1
得分: -2
const Home = () => {
const dispatch = useDispatch();
const feedPosts = useSelector((state) => state.feedPosts.posts);
useEffect(() => {
const fetchData = async () => {
if(feedPosts.length) return
try {
const response = await axios.get('http://localhost:8080/posts', {
headers: {
Authorization:authToken,
},
});
dispatch(setFeedPosts({ posts: response.data }));
} catch (error) {
console.error('Error fetching posts:', error);
}
};
fetchData();
}, []);
return (
))}
);
};
export default Home;
确保帖子的 id 是唯一的
英文:
const Home = () => {
const dispatch = useDispatch();
const feedPosts = useSelector((state) => state.feedPosts.posts);
useEffect(() => {
const fetchData = async () => {
if(feedPosts.length) return
try {
const response = await axios.get('http://localhost:8080/posts', {
headers: {
Authorization:authToken,
},
});
dispatch(setFeedPosts({ posts: response.data }));
} catch (error) {
console.error('Error fetching posts:', error);
}
};
fetchData();
}, []);
return (
<div className="homepage">
<div className="post-container">
{feedPosts.map((post) => (
<PostComponent
key={post.id}
firstName={post.firstName}
lastName={post.lastName}
userId={post.userId}
content={post.content}
/>
))}
</div>
</div>
);
};
export default Home;
make sure the post id's are unique
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论