如何在Reactjs中创建一个不被事件监听器调用的函数?

我是 ReactJS 的初学者,正在尝试创建一个简单的测验应用程序。我想要做的可以在selectionQues()函数中看到。


import React,{useState,useEffect} from 'react';

import './App.css';

import Question from './components/Question';



function App() {


  const [ques, setques] = useState([]);

  const [currentQues, setcurrentQues] = useState([]);


  //importing ques using api

  useEffect(() =>{

    fetch('https://opentdb.com/api.php?amount=20&category=18&difficulty=medium&type=multiple')

    .then((res)=> res.json())

    .then((question) => {

      setques(question.results);

    });


  },[setques])



  //selecting 5 ques at random for our quiz


  const selectingQues = () => {

    let curr=[];

    let qlen=ques.length;

    for(let i=0;i<5;i++){

      let selector= Math.floor(Math.random()*qlen);

      curr[i]=ques[selector];

    }

    setcurrentQues(curr);

    // console.log(ques);

  }


  return (

    <div className="App">

        <Question currentQues={currentQues}/>

    </div>

  );

}


export default App;

现在我想做的是调用此 SelectingQues() 而不显式使用 onClick 监听器或类似的东西。使用 useEffect 可以实现这一点吗?但我希望它在调用第一个 useEffect 后执行。


问题组件未附加,因为它只是显示问题。


九州编程
浏览 37回答 1
1回答

饮歌长啸

想法:主要想法是在 API 调用中获取 Questions 数组,并确保在那里随机获取 5 个问题。我的做法是,一旦我从 API 调用接收到数据,我就会执行promise chaining并处理所有代码,以在另一个then()块中获取 5 个随机问题。当我收到 5 个随机问题时,我将状态保存为currentQues.Codesandbox 演示import React, { useState, useEffect } from "react";import "./App.css";function App() {&nbsp; const [currentQues, setcurrentQues] = useState([]);&nbsp; //importing ques using api&nbsp; useEffect(() => {&nbsp; &nbsp; selectingQues();&nbsp; }, []);&nbsp; // selecting 5 ques at random for our quiz&nbsp; const selectingQues = async () => {&nbsp; &nbsp; const response = await fetch(&nbsp; &nbsp; &nbsp; "https://opentdb.com/api.php?amount=20&category=18&difficulty=medium&type=multiple"&nbsp; &nbsp; );&nbsp; &nbsp; const data = await response.json();&nbsp; &nbsp; console.log(data);&nbsp; &nbsp; const initialQuestions = data.results;&nbsp; &nbsp; let curr = [];&nbsp; &nbsp; // console.log(initialQuestions.length);&nbsp; &nbsp; let length = initialQuestions.length;&nbsp; &nbsp; for (let i = 0; i < 5; i++) {&nbsp; &nbsp; &nbsp; let selector = Math.floor(Math.random() * length);&nbsp; &nbsp; &nbsp; curr[i] = initialQuestions[selector];&nbsp; &nbsp; }&nbsp; &nbsp; setcurrentQues(curr);&nbsp; };&nbsp; return (&nbsp; &nbsp; <div className="App">&nbsp; &nbsp; &nbsp; {currentQues.length > 0 && <Question currentQuestions={currentQues} />}&nbsp; &nbsp; </div>&nbsp; );}export default App;const Question = ({ currentQuestions }) => {&nbsp; // const { question, correct_answer } = question;&nbsp; console.log(currentQuestions);&nbsp; return (&nbsp; &nbsp; <>&nbsp; &nbsp; &nbsp; {currentQuestions.map((question) => (&nbsp; &nbsp; &nbsp; &nbsp; <div key={question.question}>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <strong>Question:</strong> {question.question}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <strong>Answer:</strong> {question["correct_answer"]}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </p>&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; ))}&nbsp; &nbsp; </>&nbsp; );};
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript