React组件多次渲染。

huangapple go评论98阅读模式
英文:

React component getting rendered multiple times

问题

feedPosts 数组被迭代了 3 次,其中从存储中获取了帖子,尽管我已经为 postComponent 添加了 key 属性,但我仍然收到了添加 key 的错误。

  1. const Home = () => {
  2. const navigate = useNavigate();
  3. const dispatch = useDispatch();
  4. const authToken = Cookies.get("jwtToken");
  5. const feedPosts = useSelector(state => state.feedPosts.posts);
  6. useEffect(() => {
  7. axios.get("http://localhost:8080/posts", {
  8. headers: {
  9. 'authorization': authToken
  10. }
  11. }).then((posts) => {
  12. dispatch(setFeedPosts({ posts: posts.data }))
  13. })
  14. }, []);
  15. return (
  16. <div className="homepage">
  17. <div className="post-container">
  18. {feedPosts.map((post) =>
  19. <PostComponent key={post.id}
  20. firstName={post.firstName}
  21. lastName={post.lastName}
  22. userId={post.userId}
  23. content={post.content}
  24. />
  25. )}
  26. </div>
  27. </div>
  28. )
  29. }
英文:

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

  1. const Home = ()=&gt;{
  2. const navigate = useNavigate();
  3. const dispatch = useDispatch();
  4. const authToken = Cookies.get(&quot;jwtToken&quot;);
  5. const feedPosts = useSelector(state =&gt; state.feedPosts.posts);
  6. useEffect(()=&gt;{
  7. axios.get(&quot;http://localhost:8080/posts&quot;,{
  8. headers:{
  9. &#39;authorization&#39;: authToken
  10. }}).then((posts)=&gt;{
  11. dispatch(setFeedPosts({posts: posts.data}))
  12. })
  13. },[]);
  14. return(
  15. &lt;div className=&quot;homepage&quot;&gt;
  16. &lt;div className=&quot;post-container&quot;&gt;
  17. {feedPosts.map((post)=&gt;
  18. &lt;PostComponent key={post.id}
  19. firstName={post.firstName}
  20. lastName={post.lastName}
  21. userId={post.userId}
  22. content={post.content}
  23. /&gt;
  24. )}
  25. &lt;/div&gt;
  26. &lt;/div&gt;
  27. )
  28. }

答案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);
}
};

  1. fetchData();

}, []);

return (

{feedPosts.map((post) => (

))}

);
};
export default Home;
确保帖子的 id 是唯一的

英文:
  1. const Home = () =&gt; {
  2. const dispatch = useDispatch();
  3. const feedPosts = useSelector((state) =&gt; state.feedPosts.posts);
  4. useEffect(() =&gt; {
  5. const fetchData = async () =&gt; {
  6. if(feedPosts.length) return
  7. try {
  8. const response = await axios.get(&#39;http://localhost:8080/posts&#39;, {
  9. headers: {
  10. Authorization:authToken,
  11. },
  12. });
  13. dispatch(setFeedPosts({ posts: response.data }));
  14. } catch (error) {
  15. console.error(&#39;Error fetching posts:&#39;, error);
  16. }
  17. };
  18. fetchData();
  19. }, []);
  20. return (
  21. &lt;div className=&quot;homepage&quot;&gt;
  22. &lt;div className=&quot;post-container&quot;&gt;
  23. {feedPosts.map((post) =&gt; (
  24. &lt;PostComponent
  25. key={post.id}
  26. firstName={post.firstName}
  27. lastName={post.lastName}
  28. userId={post.userId}
  29. content={post.content}
  30. /&gt;
  31. ))}
  32. &lt;/div&gt;
  33. &lt;/div&gt;
  34. );

};
export default Home;
make sure the post id's are unique

huangapple
  • 本文由 发表于 2023年6月13日 17:05:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/76463306.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定