0

我正在使用上下文挂钩来处理本机反应中的状态。我想通过执行 API 调用的异步函数初始化状态,然后通过 useState 返回初始状态。那是我尝试为“touristyOptions”设置初始状态,但这不起作用。我怀疑它是由于异步功能?

**This is my Context/Provider**
    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?
4

1 回答 1

1

请试试这个。

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 (
//    ...
  );
};
于 2020-05-09T09:45:35.757 回答