当我使用Firebase数据库时React.useState不保存信息

时间:2019-11-20 22:16:47

标签: javascript reactjs firebase firebase-realtime-database react-hooks

我想从Firebase实时数据库中获取一些数据。我有这个:

function useGetDatabase(firebase) {
  const [characters, setCharacters] = useState([]);
  const [loadin, setLoadin] = useState(false);

  useEffect(() => {
    function get() {
      setLoadin(true);
      console.log(firebase.getFavoriteCharacters().once("value"));
      firebase.getFavoriteCharacters().once('value').then(function(snapshot) {
        setCharacters(snapshot.val());  //Here I save data in characters with useState
        console.log(snapshot.val());   //Returns data, the output is: [1,2,3]
      });
      setLoadin(false);
    }
    get();
    console.log(characters);   //Doesn't save data, the output is: []
  }, []);
  setCharacters([1]);   //If a put it outside of useEffect it works
  return { characters, loadin };
}

为什么那不保存我的数据?

0 个答案:

没有答案