redux React组件渲染多次

h79rfbju  于 2023-06-23  发布在  React
关注(0)|答案(1)|浏览(122)

feedPosts数组迭代了3次,其中帖子是从存储中提取的,虽然我已经添加了关键prop到postComponent,但我得到了错误的添加一个关键

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> 
    )
}
zbsbpyhn

zbsbpyhn1#

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;确保文章ID是唯一的

相关问题