我正在尝试创建一个登录会话(当用户刷新浏览器时),连接到Firebase实时数据库。
它正在工作,但我不断收到此错误。
重新渲染过多。 React限制了渲染次数,以防止 无限循环。
我的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>
);
}
答案 0 :(得分:4)
我会说使用useState
钩子。
您的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,这会导致重新渲染,并且再次发生,从而导致无限循环。