尝试刷新usestate时为什么程序会中断?

时间:2019-06-26 18:07:25

标签: javascript reactjs react-hooks

当我尝试刷新usestate时,我的程序就中断了。有问题的行是“ 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;

1 个答案:

答案 0 :(得分:0)

发生这种情况的原因是,您调用loadChet,然后调用setMesses,这会使组件重新渲染并再次调用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>
    );
}