当我尝试刷新程序时,我的程序就会破裂。有问题的行是" setMesses(_messages(;"。我试图使美国人资本化,但没有任何改变。
import React, {useState} from 'react';
import Message from './Message';
import * as firebase from "firebase";
function MessContainer() {
let counter = 0;
let _messages = [];
const [messes, setMesses] = useState([{this: null}]);
firebase.database().ref().child('counter').on('value', function(snapshot){
counter = snapshot.child("counter").val();
});
function load(_counter){
firebase.database().ref().child('messages/' + _counter).on('value', function(snapshot){
let _chet = {};
let _name = snapshot.child("name").val();
_chet.mess = _name + ": " + snapshot.child("message").val();
if(_name === document.getElementById("name").value){
_chet.status = "right";
} else {
_chet.status = "left";
}
_messages.push(_chet);
});
}
function loadChet(){
_messages = [];
for(let i = 0; i < counter; i++){
load(i);
}
console.log(_messages);
setMesses(_messages);
setTimeout(loadChet, 1000);
}
loadChet();
return (
<div>{messes.map(_mess => (
<Message mess={_mess.mess} status={_mess.status} />
))}
</div>
);
}
export default MessContainer;
发生这种情况的原因是因为您致电 loadChet
,并且该调用 setMesses
wich wich wich wich wich wich wich wich wich wich wich wich with con rerender并再次致电 loadChet
,导致无限循环。
您不应该在功能上调用loadChet
,也许使用useEffect
并仅调用一次。您何时需要致电loadChet
?
编辑:
尝试这个
function MessContainer() {
let counter = 0;
let _messages = [];
const [messes, setMesses] = useState([{this: null}]);
firebase.database().ref().child('counter').on('value', function(snapshot){
counter = snapshot.child("counter").val();
});
function load(_counter){
firebase.database().ref().child('messages/' + _counter).on('value', function(snapshot){
let _chet = {};
let _name = snapshot.child("name").val();
_chet.mess = _name + ": " + snapshot.child("message").val();
if(_name === document.getElementById("name").value){
_chet.status = "right";
} else {
_chet.status = "left";
}
_messages.push(_chet);
});
}
function loadChet(){
_messages = [];
for(let i = 0; i < counter; i++){
load(i);
}
console.log(_messages);
setMesses(_messages);
setTimeout(loadChet, 1000);
}
useEffect(() => {
loadChet();
}, [])
return (
<div>{messes.map(_mess => (
<Message mess={_mess.mess} status={_mess.status} />
))}
</div>
);
}