在使用React.js时,出现了无法在Web浏览器中显示API数据的问题。

huangapple go评论69阅读模式
英文:

Issue getting API data to show in web browser using react.js

问题

以下是您要的代码部分的中文翻译:

Spin Wheel组件:

import React, { useState, useContext } from 'react';
import PlayerContext from '../context/PlayerContext';
import TriviaAPI from '../services/TriviaAPI';
import '../styles/CategorySpinWheel.css';
import { useNavigate } from "react-router-dom";

export default function CategorySpinWheel() {
    // ... (略去未翻译的部分)
  
    const spinWheel = () => {
        setIsSpinning(true);
        const randomCategory = categories[Math.floor(Math.random() * categories.length)];
        TriviaAPI(randomCategory.uri, difficulty).then(data => {
            resetCurrentQuestion(data);
        })
        setRandomCategoryClass(randomCategory.class);
        setTimeout(() => {
            setSpinResult(randomCategory);
            setIsSpinning(false);
            setScreen("chosen");
        }, 6000);
    };
  
    return (
        <div>
            <div>
                <div>
                    <p>Hearts</p>
                    <p>Score: 200</p>
                </div>
                <h2>CATEGORY SPIN WHEEL</h2>
                <div id="wheel-div">
                    <img src={process.env.PUBLIC_URL + '/images/wheel.png'} alt="spinning image" className={`${randomCategoryClass} wheel`} />
                    <img src={process.env.PUBLIC_URL + '/images/WheelArrow.png'} alt="spinning image" className='wheel-arrow' />
                </div>
                {spinButtonVisible && 
                <button onClick={() => {
                    setSpinButtonVisible(false);
                    spinWheel();
                }}>SPIN</button>}
            </div>
            {screen === "chosen" &&
            <div className='picked-screen'>
                <p>Your category is:</p>
                <p>{spinResult?.name}</p>
                <button onClick={() => {
                    setScreen("spin");
                    setRandomCategoryClass("");
                    setSpinButtonVisible(true);
                    navigate('/question');
                }}>GO TO QUESTION</button>
            </div>}
        </div>
    );
}

Question组件:

import React, { useContext } from 'react';
import PlayerContext from '../context/PlayerContext';

export default function Question() {
    const { currentQuestion, pastQuestions, score, hearts, difficulty, resetCurrentQuestion, pushPastQuestions, resetScore, addScore, resetHearts, deleteHeart, resetDifficulty } = useContext(PlayerContext);
    let wrongAnswers = currentQuestion?.incorrectAnswers;
    let answers = [currentQuestion?.correctAnswer];
    for (let i = answers.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [answers[i], answers[j]] = [answers[j], answers[i]];
    }
  
    return (
        <div>
            <h1>{currentQuestion?.category}</h1>
            <p>{currentQuestion?.question}</p>
            {answers.map(answer => 
                <button>{answer}</button>
            )}
        </div>
    );
}

PlayerContext:

import { createContext } from "react";

export interface Question {
    "category": string,
    "id": string,
    "correctAnswer": string,
    "incorrectAnswers": string[],
    "question": string,
    "difficulty": string
}

export interface PlayerContextModel {
    currentQuestion: Question | null;
    pastQuestions: Question[];
    score: number;
    hearts: number;
    difficulty: string;
    resetCurrentQuestion: (question: Question) => void;
    pushPastQuestions: (question: Question) => void;
    resetScore: () => void;
    addScore: () => void;
    resetHearts: () => void;
    deleteHeart: () => void;
    resetDifficulty: (diff: string) => void;
}

const defaultValue: PlayerContextModel = {
    currentQuestion: null,
    pastQuestions: [],
    score: 0,
    hearts: 0,
    difficulty: "easy",
    resetCurrentQuestion: () => {},
    pushPastQuestions: () => {},
    resetScore: () => {},
    addScore: () => {},
    resetHearts: () => {},
    deleteHeart: () => {},
    resetDifficulty: () => {}
}

const PlayerContext = createContext(defaultValue);
export default PlayerContext;

PlayerContextProvider:

import React, { ReactNode, useState, useContext } from 'react';
import { Question } from './PlayerContext';
import PlayerContext from './PlayerContext';

interface Props { children: ReactNode; }

export default function PlayerContextProvider({ children }: Props) {
    const [currentQuestion, setCurrentQuestion] = useState<Question | null>(null);
    const [pastQuestions, setPastQuestions] = useState<Question[]>([]);
    const [score, setScore] = useState<number>(0);
    const [hearts, setHearts] = useState<number>(0);
    const [difficulty, setDifficulty] = useState<string>("easy");
  
    function resetCurrentQuestion(question: Question): void {
        setCurrentQuestion(question)
    }
    function pushPastQuestions(question: Question): void {
        setPastQuestions(prev => [...prev, question]);
    }
    function resetScore(): void {
        setScore(0);
    }
    function addScore(): void {
        setScore(score + 100);
    }
    function resetHearts(): void {
        setHearts(0);
    }
    function deleteHeart(): void {
        setHearts(hearts - 1);
    }
    function resetDifficulty(diff: string): void {
        setDifficulty(diff);
    }
  
    return (
        <PlayerContext.Provider value={{ currentQuestion, pastQuestions, score, hearts, difficulty, resetCurrentQuestion, pushPastQuestions, resetScore, addScore, resetHearts, deleteHeart, resetDifficulty }}>
            {children}
        </PlayerContext.Provider>
    );
}

TriviaAPI服务:

import axios from "axios";
import { Question } from "../context/PlayerContext";

export default function TriviaAPI(category: string, difficulty: string): Promise<Question> {
    return axios
        .get<Question>(`https://the-trivia-api.com/api/questions?categories=${category}&limit=1&difficulty=${difficulty}`)
        .then((res) => {
            return res.data;
        })
}

请注意,这些翻译是为了代码部分,不包括注释或任何其他额外内容。

英文:

I am trying to create a trivia game using React.js Typescript and The Trivia API. I am transferring data through components using useContext, and am navigating through components using react-router-dom. When I move from the Category Spinning Wheel to the question, I am not seeing any text from the question. Any help would be appreciated!

This is the Spin Wheel component:

import React, {useState, useContext} from &#39;react&#39;;
import PlayerContext from &#39;../context/PlayerContext&#39;;
import TriviaAPI from &#39;../services/TriviaAPI&#39;;
import &#39;../styles/CategorySpinWheel.css&#39;;
import {useNavigate} from &quot;react-router-dom&quot;;
export default function CategorySpinWheel() {
interface Category {
id: number;
name: string;
class: string;
uri: string
}
const navigate = useNavigate();
const{currentQuestion, pastQuestions, score, hearts, difficulty, resetCurrentQuestion, pushPastQuestions, resetScore, addScore, resetHearts, deleteHeart, resetDifficulty} = useContext(PlayerContext);
const categories: Category[] = [
{ id: 1, name: &#39;GENERAL KNOWLEDGE&#39;, class: &quot;general-knowledge-spin&quot;, uri: &quot;general_knowledge&quot; },
{ id: 2, name: &#39;GEOGRAPHY&#39;, class: &quot;geography-spin&quot;, uri: &quot;geography&quot; },
{ id: 3, name: &#39;FILM &amp; TV&#39;, class: &quot;film-tv-spin&quot; , uri: &quot;film_and_tv&quot;},
{ id: 4, name: &#39;HISTORY&#39;, class: &quot;history-spin&quot;, uri: &quot;history&quot; },
{ id: 5, name: &#39;MUSIC&#39;, class: &quot;music-spin&quot;, uri: &quot;music&quot; },
{ id: 6, name: &#39;FOOD &amp; DRINK&#39;, class: &quot;food-drink-spin&quot;, uri: &quot;food_and_drink&quot; },
{ id: 7, name: &#39;SCIENCE&#39;, class: &quot;science-spin&quot;, uri: &quot;science&quot; },
{ id: 8, name: &#39;ARTS &amp; LITERATURE&#39;, class: &quot;arts-literature-spin&quot;, uri: &quot;arts_and_literature&quot; },
{ id: 9, name: &#39;SPORT &amp; LEISURE&#39;, class: &quot;sport-leisure-spin&quot;, uri: &quot;sport_and_leisure&quot; },
{ id: 10, name: &#39;SOCIETY &amp; CULTURE&#39;, class: &quot;society-culture-spin&quot;, uri: &quot;society_and_culture&quot; }
];
const [screen, setScreen] = useState(&quot;spin&quot;);
const [spinResult, setSpinResult] = useState&lt;Category | null&gt;(null);
const [isSpinning, setIsSpinning] = useState(false);
const [randomCategoryClass, setRandomCategoryClass] = useState&lt;string&gt;(&quot;&quot;);
const [spinButtonVisible, setSpinButtonVisible] = useState(true);
const spinWheel = () =&gt; {
setIsSpinning(true);
const randomCategory = categories[Math.floor(Math.random() * categories.length)];
TriviaAPI(randomCategory.uri, difficulty).then(data =&gt; {
resetCurrentQuestion(data);
})
setRandomCategoryClass(randomCategory.class);
setTimeout(() =&gt; {
setSpinResult(randomCategory);
setIsSpinning(false);
setScreen(&quot;chosen&quot;);
}, 6000);
};
return (
&lt;div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;p&gt;Hearts&lt;/p&gt;
&lt;p&gt;Score: 200&lt;/p&gt;
&lt;/div&gt;
&lt;h2&gt;CATEGORY SPIN WHEEL&lt;/h2&gt;
&lt;div id=&quot;wheel-div&quot;&gt;
&lt;img src={process.env.PUBLIC_URL + &#39;/images/wheel.png&#39;} alt=&quot;spinning image&quot; className={`${randomCategoryClass} wheel`} /&gt;
&lt;img src={process.env.PUBLIC_URL + &#39;/images/WheelArrow.png&#39;} alt=&quot;spinning image&quot; className=&#39;wheel-arrow&#39;/&gt;
&lt;/div&gt;
{
spinButtonVisible &amp;&amp; 
&lt;button onClick={() =&gt; {
setSpinButtonVisible(false);
spinWheel();
}
}&gt;SPIN&lt;/button&gt;
}
&lt;/div&gt;
{
screen === &quot;chosen&quot; &amp;&amp;
&lt;div className=&#39;picked-screen&#39;&gt;
&lt;p&gt;Your category is:&lt;/p&gt;
&lt;p&gt;{spinResult?.name}&lt;/p&gt;
&lt;button onClick={() =&gt; {
setScreen(&quot;spin&quot;);
setRandomCategoryClass(&quot;&quot;);
setSpinButtonVisible(true);
navigate(&#39;/question&#39;);
}}&gt;GO TO QUESTION&lt;/button&gt;
&lt;/div&gt;
}
&lt;/div&gt;
)
}

This is the question component:

import React, {useContext} from &#39;react&#39;
import PlayerContext from &#39;../context/PlayerContext&#39;
export default function Question() {
const{currentQuestion, pastQuestions, score, hearts, difficulty, resetCurrentQuestion, pushPastQuestions, resetScore, addScore, resetHearts, deleteHeart, resetDifficulty} = useContext(PlayerContext);
let wrongAnswers = currentQuestion?.incorrectAnswers;
let answers = [currentQuestion?.correctAnswer];
for (let i = answers.length - 1; i &gt; 0; i--){
const j = Math.floor(Math.random() * (i + 1));
[answers[i], answers[j]] = [answers[j], answers[i]];
}
return (
&lt;div&gt;
&lt;h1&gt;{currentQuestion?.category}&lt;/h1&gt;
&lt;p&gt;{currentQuestion?.question}&lt;/p&gt;
{answers.map(answer =&gt; 
&lt;button&gt;{answer}&lt;/button&gt;
)}
&lt;/div&gt;
)
}

this is the context:

import { createContext } from &quot;react&quot;;
export interface Question{
&quot;category&quot;: string,
&quot;id&quot;: string,
&quot;correctAnswer&quot;: string,
&quot;incorrectAnswers&quot;: string[],
&quot;question&quot;: string,
&quot;difficulty&quot;: string
}
export interface PlayerContextModel{
currentQuestion: Question | null;
pastQuestions: Question[];
score: number,
hearts: number,
difficulty: string,
resetCurrentQuestion: (question: Question) =&gt; void,
pushPastQuestions: (question: Question) =&gt; void,
resetScore: () =&gt; void,
addScore: () =&gt; void,
resetHearts: () =&gt; void,
deleteHeart: () =&gt; void,
resetDifficulty: (diff: string) =&gt; void
}
const defaultValue: PlayerContextModel = {
currentQuestion: null,
pastQuestions: [],
score: 0,
hearts: 0,
difficulty: &quot;easy&quot;,
resetCurrentQuestion: () =&gt; {},
pushPastQuestions: () =&gt; {},
resetScore: () =&gt; {},
addScore:() =&gt; {},
resetHearts:() =&gt; {},
deleteHeart:() =&gt; {},
resetDifficulty:() =&gt; {}
}
const PlayerContext = createContext(defaultValue);
export default PlayerContext;

This is the context provider:

import React, {ReactNode, useState, useContext} from &#39;react&#39;
import { Question } from &#39;./PlayerContext&#39;;
import PlayerContext from &#39;./PlayerContext&#39;;
interface Props {children: ReactNode; }
export default function PlayerContextProvider({children}: Props) {
const [currentQuestion, setCurrentQuestion] = useState&lt;Question | null&gt;(null);
const [pastQuestions, setPastQuestions] = useState&lt;Question[]&gt;([])
const [score, setScore] = useState&lt;number&gt;(0);
const [hearts, setHearts] = useState&lt;number&gt;(0);
const [difficulty, setDifficulty] = useState&lt;string&gt;(&quot;easy&quot;);
function resetCurrentQuestion(question: Question): void {
setCurrentQuestion(question)
}
function pushPastQuestions(question: Question): void {
setPastQuestions(prev =&gt; [...prev, question]);
}
function resetScore(): void {
setScore(0);
}
function addScore(): void {
setScore(score + 100);
}
function resetHearts(): void {
setHearts(0);
}
function deleteHeart(): void {
setHearts(hearts - 1);
}
function resetDifficulty(diff: string): void {
setDifficulty(diff);
}
return (
&lt;PlayerContext.Provider value={{currentQuestion, pastQuestions, score, hearts, difficulty, resetCurrentQuestion, pushPastQuestions, resetScore, addScore, resetHearts, deleteHeart, resetDifficulty}}&gt;
{children}
&lt;/PlayerContext.Provider&gt;
)
}

And this is the service I am using to get the API Data:

import axios from &quot;axios&quot;;
import { Question } from &quot;../context/PlayerContext&quot;;
export default function TriviaAPI(category: string, difficulty: string): Promise&lt;Question&gt; {
return axios
.get&lt;Question&gt;(`https://the-trivia-api.com/api/questions?categories=${category}&amp;limit=1&amp;difficulty=${difficulty}`)
.then((res) =&gt; {
return res.data;
})
}

答案1

得分: 1

res.data 是一个数组,使用 res.data[0] 来获取(第一个)问题本身。

英文:

res.data is an array, use res.data[0] to get the (first) question itself.

huangapple
  • 本文由 发表于 2023年2月27日 06:47:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/75575458.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定