在 context/provider react native 中初始化异步函数中的状态

Initialize state in async function within context/provider react native

我正在使用 Context Hooks 来处理 React Native 中的状态。我想通过执行 API 调用的异步函数初始化状态,然后通过 useState return 初始化状态。那是我尝试为 "touristyOptions" 设置初始状态,但这不起作用。我怀疑是异步函数引起的?

**This is my Context/Provider**
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre><code>    import React, { useState, useEffect } from "react";
import * as firebase from "firebase";
import { levelTables } from "../config/config";

const LevelOptionsContext = React.createContext();

const LevelOptionsProvider = (props) => {
  
  const setLevelOptions = (type) => {
    let categoryRef = firebase
      .database()
      .ref(type)
      .orderByKey();
    categoryRef
      .once("value")
      .then((snapshot) => {
        let result = [];
        snapshot.forEach(function(childSnapshot) {
          let value = childSnapshot.val();
          result.push({ value, active: false });
        });
        return [...result];
      })
      .catch((error) => console.log(error))
  };

  const [touristyOptions, setTouristyOptions] = useState(
    setLevelOptions("touristy_level")
  );
  const [adventurouseOptions, setAdventurouseOptions] = useState([]);

  return (
    <LevelOptionsContext.Provider
      value={{
        adventurouseOptions,
        setAdventurouseOptions,
        touristyOptions,
        setTouristyOptions
      }}
    >
      {props.children}
    </LevelOptionsContext.Provider>
  );
};

export { LevelOptionsContext, LevelOptionsProvider };
This does not work. Anyone can give a hint?

请试试这个。

import React, { useState, useEffect } from "react";
import * as firebase from "firebase";
import { levelTables } from "../config/config";

const LevelOptionsContext = React.createContext();

const LevelOptionsProvider = (props) => {
  const [touristyOptions, setTouristyOptions] = useState([]);
  const setLevelOptions = (type) => {
    let categoryRef = firebase
      .database()
      .ref(type)
      .orderByKey();
    categoryRef
      .once("value")
      .then((snapshot) => {
        let result = [];
        snapshot.forEach(function(childSnapshot) {
          let value = childSnapshot.val();
          result.push({ value, active: false });
        });
        setTouristOptions(result)
      })
      .catch((error) => console.log(error))
  };
  useEffect(() => { setLevelOptions(); }, []);
  return (
//    ...
  );
};