如何使用useEffect编写React代码来显示数组对象的数据



我正在尝试的内容:

  1. 从字符数组中随机抽取一个字符,并显示其能力和角色
  2. 从同一数组中取其他四个唯一的随机字符名,并将其显示为选项
  3. 请注意,选项也必须有正确的答案
  4. 如果猜测的字符是正确的,分数应该增加1,否则减少1

代码:

import React, { Fragment, useEffect, useState } from "react";
import "../styles/App.css";
const characters = [
{
id: 1,
name: "Jett",
role: "Duelist",
abilities: ["TailWind", "Cloud Burst", "UpDraft", "Blade Storm"],
},
{
id: 2,
name: "Phoenix",
role: "Duelist",
abilities: ["HotHands", "Blaze", "Curve Ball", "Run It Back"],
},
{
id: 3,
name: "Yoru",
role: "Duelist",
abilities: ["GateCrash", "Fakeout", "Blind Side", "Dimensional Drift"],
},
{
id: 4,
name: "Reyna",
role: "Duelist",
abilities: ["Dismiss", "Leer", "Devour", "Empress"],
},
{
id: 5,
name: "Raze",
role: "Duelist",
abilities: ["Paint Shells", "Boom Bot", "BlastPack", "ShowStopper"],
}
];
const App = () => {
const [currChar, setCurrChar] = useState({
name: "",
role: "",
abilities: [],
options: [],
});
const [score, setScore] = useState(0);
const changeChar = () => {

}
const scoreHandler = (e) => {

};
useEffect(() => {

});
return (
<div id="main">
<div className="container">
<h1 className="header">Guess the Character</h1>
<div className="ques-area">
<div className="score" id='score'>Score: {score}</div>
<h3>The character has the following abilities:</h3>
<h4>Role: {currChar.role}</h4>
{currChar.abilities.join()}
<div className="options">
{currChar.options.map((option) => (
<button   onClick={scoreHandler}>
{option.name}
</button>
))}
</div>
</div>
</div>
</div>
);
};
export default App;
useEffect(() => {
getRandomObject(characters);
}, []);
const [score, setScore] = useState(0);
const getRandomObject = (array) => {
const optionArr = [];
for (let i = 0; i < array.length; i++) {
optionArr.push(array[Math.floor(Math.random() * array.length)]);
}
const randomObject = array[Math.floor(Math.random() * array.length)];
const obj = {
name: randomObject.name,
role: randomObject.role,
abilities: randomObject.abilities,
options: optionArr.slice(0, 4)
};
setCurrChar(obj);
};

最新更新