gpt4 book ai didi

reactjs - 太多的重新渲染。 React 限制渲染次数以防止无限循环

转载 作者:行者123 更新时间:2023-12-04 00:24:15 24 4
gpt4 key购买 nike

我正在尝试创建一个登录 session (当用户刷新浏览器时)连接到 firebase 实时数据库。

它工作正常,但我一直收到此错误。

Too many re-renders. React limits the number of renders to prevent an infinite loop.

我的 app.js

import React from 'react';

import { UserProvider } from './model/UserContext'


function App() {

return (
<div>
<UserProvider>
<Session />
<NavBar />
<Container maxWidth="sm">
<Router>
<Route path='/Login' component={Login} />
<Route path='/Dashboard' component={Dashboard} />
</Router>
</Container>
</UserProvider>
</div>
);
}

export default App;

我的 UserContext.js

import React, { useState, createContext } from 'react'
import Firebase from 'firebase'

export const UserContext = createContext();

//export const UserProvider = UserContext.Provider
//export const UserConsumer = UserContext.Consumer
// export default UserContext

export const UserProvider = props => {
const[user, setUser] = useState(
{
username:"blank",
loggendIn: false
}
);


var id = localStorage.getItem('id');
// check if its null
console.log(id);

if(id != null){
console.log('id is there');
// load user from realtime database
const dbOBJ = Firebase.database().ref().child("users").child(id);

dbOBJ.on('value', function(snapshot){
setUser(snapshot.val());
});

}else{
console.log('no id :( ');
}



return(
<UserContext.Provider value={[user, setUser]}>
{props.children}
< /UserContext.Provider>
);
}

最佳答案

我会说使用 useState 钩子(Hook)。

你的 UserContext.js

import React, { useState, createContext, useEffect } from 'react'
import Firebase from 'firebase'

export const UserContext = createContext();

//export const UserProvider = UserContext.Provider
//export const UserConsumer = UserContext.Consumer
// export default UserContext

export const UserProvider = props => {
const[user, setUser] = useState(
{
username:"blank",
loggendIn: false
}
);


var id = localStorage.getItem('id');
// check if its null
console.log(id);
useEffect(() => {
if(id != null){
console.log('id is there');
// load user from realtime database
const dbOBJ = Firebase.database().ref().child("users").child(id);

dbOBJ.on('value', function(snapshot){
setUser(snapshot.val());
});

}else{
console.log('no id :( ');
}
},[id]) // <==== this will call useEffect again if your id changes



return(
<UserContext.Provider value={[user, setUser]}>
{props.children}
< /UserContext.Provider>
);
}

出现此错误的原因是您的条件满足并且您调用了 setState 导致重新渲染并且再次发生从而导致无限循环。

关于reactjs - 太多的重新渲染。 React 限制渲染次数以防止无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58100559/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com