reactjs 数据更改后,React组件不会自行更新,而不会刷新整个页面

js4nwp54  于 2023-03-17  发布在  React
关注(0)|答案(3)|浏览(287)

我在前端使用ReactJS向Djando API发出POST请求。在发出POST请求后,我希望React组件能够自动更新,而无需刷新整个页面。我使用useEffect钩子调用my endpoint(GET)来检索刚刚更新的数据。

import React from 'react'
import CampaignList from '../components/CampaignList'
import {useState, useEffect} from 'react'


const campaignRequest = () => {
  fetch('http://localhost:8000/api/v1/campaigns/', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      email_address: "zztop1111122233344556677889910101010@gmail.com",
      first_name: "i",
      last_name: "k",
      stage: "1"
    })
  })
  .then(res => res.json())
  .then(data => console.log(data))
  .catch(error => console.log(error))
}

let Campaigns = () => {
  
  const [recipients, setRecipients] = useState([]);
  const [isLoading, setIsLoading] = useState(true);

  console.log("Campaign is re-mounted")
  useEffect(() => {
      setIsLoading(true);
      
      fetch('http://localhost:8000/api/v1/campaigns/')
      .then((res) => res.json())
      .then((data) => {
        setRecipients(data);
        setIsLoading(false);
      })
      .catch(error => console.log(error));
      
      // fetchData()
  }
  ,[]);

  if (isLoading) {
    return <p>Loading...</p>;
  }

  return (
    <div>
      <div>Campaigns</div>
      <CampaignList recipientss={recipients}/>
      {/* <div> 
        {recipients.map((recipient, index) => (
             <h3 key={index}>{recipient.email_address}
             </h3> 
            
          ))}
      </div> */}
      <button onClick={campaignRequest}>Click Me</button>
    </div>
    
  )
}

export default Campaigns
brgchamk

brgchamk1#

我想这个应该可以用。现在你每次点击的时候收件人都会更新。

import React from "react";
import CampaignList from "../components/CampaignList";
import { useState, useEffect } from "react";

let Campaigns = () => {
    const [recipients, setRecipients] = useState([]);
    const [isLoading, setIsLoading] = useState(true);

    const campaignRequest = () => {
        fetch("http://localhost:8000/api/v1/campaigns/", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify({
                email_address: "zztop1111122233344556677889910101010@gmail.com",
                first_name: "i",
                last_name: "k",
                stage: "1",
            }),
        })
            .then((res) => res.json())
            .then((data) => {
                setRecipients(data);
            })
            .catch((error) => console.log(error));
    };

    console.log("Campaign is re-mounted");
    useEffect(() => {
        campaignRequest();
        setIsLoading(false);
    }, []);

    if (isLoading) {
        return <p>Loading...</p>;
    }

    return (
        <div>
            <div>Campaigns</div>
            <CampaignList recipientss={recipients} />
            <button onClick={campaignRequest}>Click Me</button>
        </div>
    );
};

export default Campaigns;
x8goxv8g

x8goxv8g2#

这是因为您没有任何东西触发get fetch再次被调用
把这个放到你的onClick

() => {
 campaignRequest()
 setLoad(true);
 }

这就是你的使用效果

if (load) {
   ....
   setLoad(false);
 }
 }, [load])
pgx2nnw8

pgx2nnw83#

看起来您希望在单击Click Me时将一些数据POSThttp://localhost:8000/api/v1/campaigns/,然后在POST完成时自动从同一URL中GET数据。
在您的代码片段中,GET请求位于useEffect钩子内,该钩子具有一个空依赖项数组,因此它将只执行一次-在初始呈现时。
如果希望保持相同的代码结构,则必须引入一个新的状态变量来触发useEffect钩子,例如isAddCampaignLoading,然后可以将const campaignRequest = () => {...}移到Campaigns组件中,并在campaignRequest成功时更改isAddCampaignLoading的状态。你将把isAddCampaignLoading添加到你的useEffect钩子的dependencies数组中,以使它在每次isAddCampaignLoading改变时执行。我还在钩子内部添加了一个检查,以确保只有当isAddCampaignLoadingfalsecampaignRequest成功)时才获取活动。

import React from 'react'
import CampaignList from '../components/CampaignList'
import {
    useState,
    useEffect
} from 'react'

let Campaigns = () => {
    const [recipients, setRecipients] = useState([]);
    const [isFetchCampaignsLoading, setIsFetchCampaignsLoading] = useState(true);
    const [isAddCampaignLoading, setIsAddCampaignLoading] = useState(false);

    const campaignRequest = () => {
        setIsAddCampaignLoading(true)
        fetch('http://localhost:8000/api/v1/campaigns/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                email_address: "zztop1111122233344556677889910101010@gmail.com",
                first_name: "i",
                last_name: "k",
                stage: "1"
            })
        })
            .then(res => res.json())
            .then(data => console.log(data))
            .catch(error => console.log(error))
            .finally(() => setIsAddCampaignLoading(false))
    }

    console.log("Campaign is re-mounted")
    useEffect(() => {
        if (!isAddCampaignLoading) {
            setIsFetchCampaignsLoading(true);
            fetch('http://localhost:8000/api/v1/campaigns/')
                .then((res) => res.json())
                .then((data) => {
                    setRecipients(data);
                    setIsAddCampaignLoading(false);
                })
                .catch(error => console.log(error))
                .finally(() => setIsFetchCampaignsLoading(false))
        }
    }, [isAddCampaignLoading]);

    if (isFetchCampaignsLoading) {
        return <p> Loading... </p>;
    }

    return ( <div>
            <div> Campaigns </div> 
            <CampaignList recipients={recipients}/> 
            {
            /* <div> 
                        {recipients.map((recipient, index) => (
                             <h3 key={index}> 
                                {recipient.email_address}
                             </h3> 
                          ))}
                      </div> */
        } 
           <button onClick={campaignRequest}>Click Me</button> 
           </div>
    )
}

export default Campaigns

相关问题