为什么我在尝试设置状态时得到太多渲染?

Why am I getting too many renders when trying to setState?

这是我的代码。我正在从 firebase 获取数据并将其放入我的 groupDataMap.

const Home = () => {
    
    const [memberInfo, setMemberInfo] = useState('');
    const auth = getAuth();
    const user = auth.currentUser;
    const memberId = auth.currentUser.uid
    const db = getDatabase();
    const dbRef = ref(db, 'groups');
    let groupDataMap = {};

    //get group name's if member_id(user) matches member id
    onValue(dbRef, (snapshot)=> {
        const data = snapshot.val();

        for(var key in data){
            if(data.hasOwnProperty(key)){
                const groupname = data[key]
                groupDataMap = groupname
            }
        }
    })
    setMemberInfo(groupDataMap)


我正在使用 memberInfo 填充 return 中的 <li> 元素:

 return (
        <div>
            <div class="brand">
                <h1>Headline</h1>
                <p>paragraph</p>
            </div>

            <ul class="list-group container-fluid">
                <li class="list-group-item">
                {memberInfo}
                </li>
            </ul>
        </div>
    );

我不是只设置一次状态吗?

Am I not just setting the state once?

不会,setMemberInfo会被反复调用,让组件无限渲染。

了解 useEffect 钩子。

    const [memberInfo, setMemberInfo] = useState('');
    const auth = getAuth();
    const user = auth.currentUser;
    const memberId = auth.currentUser.uid

    useEffect(() => {
        const db = getDatabase();
        const dbRef = ref(db, 'groups');
        let groupDataMap = {};

        //get group name's if member_id(user) matches member id
        onValue(dbRef, (snapshot)=> {
            const data = snapshot.val();

            for(var key in data){
                if(data.hasOwnProperty(key)){
                    const groupname = data[key]
                    groupDataMap = groupname
                }
            }
        })
        setMemberInfo(groupDataMap)

    }, []); 

提示: 与您的问题类似

您将不得不使用 React 的 useEffect 钩子来设置状态。

Use this link for reference