簡體   English   中英

避免在反應組件中無限重新渲染

[英]Avoiding infinite re-rendering in react component

我有一個名為線程的 Supbase 數據庫,有 5 個條目,我正在嘗試為數據庫中的每一列創建一個新的 React 組件,但我遇到了一些問題。

它給我的問題是它正在停止程序以防止無限循環,我認為這是因為在我的代碼中,我每次渲染我知道的組件時都會更新我的 useState,但我不是確定我將如何解決這個問題。

組件.js:

import {useState} from "react";
import {supabase} from "../../utils/supabaseClient";

export default function Sidebar() {
    const [newThreads, setNewThreads] = useState([]);

    // this is where I am kinda stuck
    const threadList = [];
    (async () => {
        let {data: threads, error} = await supabase
            .from('threads')
            .select('thread_title');
        threadList.push(threads); // how do I get the current index of the loop (and limit it to only get 5 entries?)
        threadList.forEach(function (value) {
            console.log(value)
        })
    })();
    setNewThreads(threadList);

    return (
        <div className="sidebar">
            <div className="sidebar-widget">
                <span className="widget-title">New Threads</span>
            </div>
            <div className="sidebar-widget">
                <span className="widget-title">New Members</span>
                {(Object.entries(newThreads) || []).map(([key, value]) => {
                    return (
                        <div className="widget-cell">
                            <div className={"widget-cell-image"}/>
                            <div className="widget-cell-content">
                                <span className={"widget-cell-title"}>{value}</span>
                                <div className="widget-cell-values">
                                    <span className={"widget-cell-by-user"}>by harley_swift,</span>
                                    <span className={"widget-cell-time"}>22:02</span>
                                </div>
                            </div>
                        </div>
                    );
                })}

            </div>
        </div>
    )
}

任何有關解釋的幫助將不勝感激!

解決無限重新渲染問題的方法是使用useEffect獲取數據:

useEffect(() => {
    // this is where I am kinda stuck
    const threadList = [];
    (async () => {
        let {
            data: threads,
            error
        } = await supabase
            .from('threads')
            .select('thread_title');
        threadList.push(threads); // how do I get the current index of the loop (and limit it to only get 5 entries?)
        threadList.forEach(function(value) {
            console.log(value)
        })
    })();
    setNewThreads(threadList);
}, []); // note the empty dependency list

空依賴列表是您知道效果只會運行一次的方式之一。

要僅將 5 個項目添加到列表中,您可以對結果進行切片(或檢查supabase是否具有這樣做的內置方法):

threadList.push(threads.slice(0, 5));

暫無
暫無

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

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