如何在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之后执行。

问题组件没有附加,因为rn只不过是显示问题。

IDEA:主要想法是在API调用中获取问题数组,并确保在其中随机获得5个问题。我的方法是,一旦我从API调用接收到我的数据,我就执行promise chaining并处理我的所有代码,以便在另一个then()块中获得5个随机问题。当我收到我的5个随机问题时,我保存在状态currentQues中。

Codesandbox演示

import React, { useState, useEffect } from "react";
import "./App.css";
function App() {
const [currentQues, setcurrentQues] = useState([]);
//importing ques using api
useEffect(() => {
selectingQues();
}, []);
// selecting 5 ques at random for our quiz
const selectingQues = async () => {
const response = await fetch(
"https://opentdb.com/api.php?amount=20&category=18&difficulty=medium&type=multiple"
);
const data = await response.json();
console.log(data);
const initialQuestions = data.results;
let curr = [];
// console.log(initialQuestions.length);
let length = initialQuestions.length;
for (let i = 0; i < 5; i++) {
let selector = Math.floor(Math.random() * length);
curr[i] = initialQuestions[selector];
}
setcurrentQues(curr);
};
return (
<div className="App">
{currentQues.length > 0 && <Question currentQuestions={currentQues} />}
</div>
);
}
export default App;
const Question = ({ currentQuestions }) => {
// const { question, correct_answer } = question;
console.log(currentQuestions);
return (
<>
{currentQuestions.map((question) => (
<div key={question.question}>
<p>
<strong>Question:</strong> {question.question}
</p>
<p>
<strong>Answer:</strong> {question["correct_answer"]}
</p>
</div>
))}
</>
);
};

最新更新