React组件多次渲染。

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

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 = ()=&gt;{ 
    const navigate = useNavigate();
    const dispatch = useDispatch();
    const authToken = Cookies.get(&quot;jwtToken&quot;);
    const feedPosts = useSelector(state =&gt; state.feedPosts.posts);
    useEffect(()=&gt;{
      axios.get(&quot;http://localhost:8080/posts&quot;,{
    headers:{
        &#39;authorization&#39;: authToken
    }}).then((posts)=&gt;{
      dispatch(setFeedPosts({posts: posts.data}))
    })
    },[]);
    return(
      &lt;div className=&quot;homepage&quot;&gt;
        &lt;div className=&quot;post-container&quot;&gt;
          {feedPosts.map((post)=&gt;
            &lt;PostComponent key={post.id}
            firstName={post.firstName} 
            lastName={post.lastName} 
            userId={post.userId}
            content={post.content}
            /&gt;
          )}
        &lt;/div&gt;
     &lt;/div&gt; 
    )
}

答案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 (

{feedPosts.map((post) => (

))}

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

英文:
const Home = () =&gt; {
const dispatch = useDispatch();
const feedPosts = useSelector((state) =&gt; state.feedPosts.posts);

useEffect(() =&gt; {
  const fetchData = async () =&gt; {
    if(feedPosts.length) return
    try {
      const response = await axios.get(&#39;http://localhost:8080/posts&#39;, {
        headers: {
          Authorization:authToken,
        },
      });
      dispatch(setFeedPosts({ posts: response.data }));
    } catch (error) {
      console.error(&#39;Error fetching posts:&#39;, error);
    }
  };

  fetchData();
}, []);

return (
  &lt;div className=&quot;homepage&quot;&gt;
    &lt;div className=&quot;post-container&quot;&gt;
      {feedPosts.map((post) =&gt; (
        &lt;PostComponent
          key={post.id}
          firstName={post.firstName}
          lastName={post.lastName}
          userId={post.userId}
          content={post.content}
        /&gt;
      ))}
    &lt;/div&gt;
  &lt;/div&gt;
);

};
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:

确定