简体   繁体   English

Typescript,使用字符串查找枚举

[英]Typescript, using a string to lookup an enum

I am working on my first Typescript and React project.我正在研究我的第一个 Typescript 和 React 项目。 I have a quiz app at https://quiz-time-69c35.web.app/我在https://quiz-time-69c35.web.app/有一个测验应用程序

Right now selecting a category from the dropdown menu doesn't actually do anything.现在从下拉菜单中选择一个类别实际上并没有做任何事情。 I need help using the selected option to fetch questions from the selected category.我需要使用所选选项从所选类别中提取问题的帮助。

I have an enum Category.我有一个枚举类别。

export enum Category {
  ANY_CATEGORY = 0, 
  GENERAL_KNOWLEDGE = 9, 
  ENTERTAINMENT_BOOKS = 10, 
  ENTERTAINMENT_FILM = 11, 
  ENTERTAINMENT_MUSIC = 12, 
  ENTERTAINMENT_MUSICALS_AND_THEATRES = 13, 
  ENTERTAINMENT_TELEVISION = 14, 
  ENTERTAINMENT_VIDEO_GAMES = 15, 
  ENTERTAINMENT_BOARD_GAMES = 16, 
  SCIENCE_AND_NATURE = 17, 
  SCIENCE_COMPUTERS = 18, 
  SCIENCE_MATHEMATICS = 19, 
  MYTHOLOGY = 20, 
  SPORTS = 21, 
  GEOGRAPHY = 22, 
  HISTORY = 23, 
  POLITICS = 24, 
  ART = 25, 
  CELEBRITIES = 26, 
  ANIMALS = 27, 
  VEHICLES = 28, 
  ENTERTAINMENT_COMICS = 29, 
  SCIENCE_GADGETS = 30, 
  ENTERTAINMENT_JAPANESE_ANIME_AND_MANGA = 31, 
  ENTERTAINMENT_CARTOON_AND_ANIMATIONS = 32
}

A function to fetch questions at an endpoint.一个 function 在端点获取问题。

export const fetchQuizQuestions = async (amount: number, category: Category, difficulty: Difficulty) => {
  const endpoint = `https://opentdb.com/api.php?amount=${amount}&category=${category}&difficulty=${difficulty}&type=multiple`;
  const data = await (await fetch(endpoint)).json();
  return data.results.map((question: Question) => (
    {
      ...question,
      answers: shuffleArray([...question.incorrect_answers, question.correct_answer])
    }
  ));
}

The user selects a category from a menu using the following onChange function.用户使用以下 onChange function 从菜单中选择类别。 The selected option is stored in the state as selectedOption as type OptionType.所选选项存储在 state 中,作为 selectedOption 类型为 OptionType。

Console logging selectedOption here returns {value: "ENTERTAINMENT_BOOKS", label: "Books"}控制台记录 selectedOption 此处返回 {value: "ENTERTAINMENT_BOOKS", label: "Books"}

onChange={(selectedOption) => {
           const value = (selectedOption as OptionType).value;
           setSelectedOption(value)
           console.log(selectedOption)
          }}
type OptionType = { 
  label: any;
  value: any; 
}
const [selectedOption, setSelectedOption] = useState<OptionType>();

The user then presses a button to call the following function and begin the quiz.然后用户按下按钮调用以下 function 并开始测验。

Console logging category or selectedOption only returns the value of selectedOption as string and not the whole object.控制台日志记录类别或 selectedOption 仅将 selectedOption 的值作为字符串返回,而不是整个 object。 Why is this case when the whole object was logged in the onChange function?当整个 object 都记录在 onChange function 中时,为什么会出现这种情况?

const startTrivia = async () => {
    setLoading(true);
    setGameOver(false);


    const category = selectedOption
    console.log(category)

    const newQuestions = await fetchQuizQuestions(
      TOTAL_QUESTIONS,
      Category["SCIENCE_AND_NATURE"],
      Difficulty.HARD,
    );

    setQuestions(newQuestions);
    setScore(0);
    setUserAnswers([]);
    setNumber(0);
    setLoading(false);
  }

How can I use the string from the value in selectedOption to look up the member in the Category enum?如何使用 selectedOption 值中的字符串来查找 Category 枚举中的成员?

I tried Category[category] and Category[category?.value] but neither of them worked.我尝试了Category[category]Category[category?.value]但它们都不起作用。

I am brand new to Typescript so any feedback is appreciated and if I'm going about this in the wrong manner please let me know.我是 Typescript 的全新用户,因此感谢您提供任何反馈,如果我以错误的方式处理此问题,请告诉我。

You are calling setSelectedOption with the .value property only.您仅使用.value属性调用setSelectedOption See the .value at the end of the first line?看到第一行末尾的.value了吗?

const value = (selectedOption as OptionType).value;
setSelectedOption(value);

You would get an error on this if you were using stricter types.如果你使用更严格的类型,你会得到一个错误。 Unfortunately OptionType['value'] is any and any is assignable to anything, so it's ok to call setSelectedOption(any) .不幸的是OptionType['value']any并且any可以分配给任何东西,所以可以调用setSelectedOption(any)

You may have changed your code since posting this because it appears to be logging the value as the number value from the enum rather than the key "ENTERTAINMENT_BOOKS" .自发布此代码以来,您可能已经更改了代码,因为它似乎将value记录为enum中的number值,而不是键"ENTERTAINMENT_BOOKS" Try this:尝试这个:

type OptionType = { 
  label: string;
  value: Category; // is a `number`, but only the specific numbers in the enum
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM