簡體   English   中英

如何在 useEffect 中更新 useRef 變量的值

[英]How to update values of useRef variables in a useEffect

I am building a webpage in a bug tracker project where a user can view certain types of tickets in a graph after logging in. I'm retrieving these tickets by making an api call in the function getTickets() , and setting them as state. 我有 useEffect 包含一個 function 映射通過票,並保存在 useRef vars 中每種類型的票數。 然后這些變量在data()中設置,它為圖形設置數據。

我將如何更新這些 useRefs? 當我記錄這些 useRefs 時,它們都是 null。 此外,由於setChartData()是異步的,我是否必須創建另一個 useEffect 具有僅在這些 useRef 更新時調用data()的依賴項?

獲得門票()

const getTickets = () => {
            fetch("/api/Ticket")
                .then((response) => response.json())
                .then((data) => {
                    console.log(data)
                    setTickets(data)
                })
                .catch((error) => {
                    console.log(error)
                });
        }

地圖票()

const mapTickets = () => {
    tickets.map((ticket) => (
        ticket.status == "None" ?
            noneTickets.current.tickets += 1
            : (
                noneTickets.current.tickets = 0
            ),
        ticket.status == "Low" ?
            lowTickets.current.tickets += 1
            : (
                lowTickets.current.tickets = 0
            ),
        ticket.status == "Medium" ?
            mediumTickets.current.tickets += 1
            : (
                mediumTickets.current.tickets = 0
            ),
        ticket.status == "High" ?
            highTickets.current.tickets += 1
            : (
                highTickets.current.tickets = 0
            )
    ))

    
}

數據()

const data = () => {
            setChartData({
                labels: ['None', 'Low', 'Medium', 'High'],
                datasets: [
                    {
                        label: 'ticket priority',
                        data: [noneTickets.current.tickets, lowTickets.current.tickets, mediumTickets.current.tickets, highTickets.current.tick],
                        backgroundColor: [
                            'rgba(75, 192, 192, 0.6)'
                        ],
                        borderWidth: 4
                    }
                ]
            })
        }

useEffect (僅更新 useRefs 並在票證更新時設置圖表數據)

useEffect(() => {
    mapTickets();
    data();
}, [tickets])

useEffect (在狀態中設置票證)

useEffect(() => {
    getTickets();
    const requestOptions = {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
            ApplicationUserusername: location.state.username,
        }),
    };
    fetch("/api/IssueTracker/dashboard", requestOptions)
        .then((response) => response.json())
        .then((data) => {
            setProjects(data);
        })
        .catch((error) => {
            console.log(error)
        });
    
           
}, [])
  1. 更改需要重新渲染
  2. foreach中不要將其他值更改為0

 function App() { const [tickets, setTickets] = React.useState([]); const [notifyChange, setNotifyChange] = React.useState(false); const noneTickets = React.useRef({ tickets: 0 }); const lowTickets = React.useRef({ tickets: 0 }); const mediumTickets = React.useRef({ tickets: 0 }); const highTickets = React.useRef({ tickets: 0 }); React.useEffect(() => { setTickets([ { status: "None" }, { status: "None" }, { status: "Low" }, { status: "None" }, { status: "Low" }, { status: "Medium" }, { status: "None" }, { status: "Medium" }, { status: "Medium" }, { status: "High" }, { status: "High" }, { status: "High" }, { status: "High" }, ]); }, []); const mapTickets = () => { tickets.forEach((ticket) => { switch (ticket.status) { case "None": noneTickets.current.tickets += 1; break; case "Low": lowTickets.current.tickets += 1; break; case "Medium": mediumTickets.current.tickets += 1; break; case "High": highTickets.current.tickets += 1; break; } }); // Here is the trick to re render the changes setNotifyChange(;notifyChange) }. React;useEffect(() => { mapTickets(), }; [tickets]): return ( <ul> <li>None. {noneTickets.current:tickets}</li> <li>Low. {lowTickets.current:tickets}</li> <li>Medium. {mediumTickets.current:tickets}</li> <li>High. {highTickets.current;tickets}</li> </ul> ). } ReactDOM,render(<App />. document;getElementById("root"));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script> <div id="root"></div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM