React组件设置状态,使用一个空数组



到目前为止,我的组件,我试图从API一次获取数据,这将存储一个随机选择(目前10)的对象在数组correctAnswerArray。我使用splice()来确保相同的对象不是随机选择的。我把这些随机选择的对象推到新的数组中,然后尝试用setCorrectAnswer(correctAnswerArray)来设置状态correctAnswer

当我在下一行记录状态时,状态(correctAnswer)仍然为空。话虽如此,我不确定为什么状态是空的,当correctAnswerArray我推到它里面有项目。如有任何帮助,不胜感激。

import React, { useState, useEffect } from 'react'
import axios from 'axios';
const URL = 'https://restcountries.com/v3.1/all';
const Game = () => {
const [currentQuestion, setCurrentQuestion] = useState(0);
const [currentChoices, setCurrentChoices] = useState([]);
const [correctAnswer, setCorrectAnswer] = useState([]);
const [score, setScore] = useState(0);
useEffect(() => {
const fetchData = async () => {
const res = await axios.get(URL);
console.log(res);
const correctAnswerArray = [];

for (let i = 0; i < 10; i++) {
let country = res.data[Math.floor(Math.random() * res.data.length)];
let idx = res.data.indexOf(country);
res.data.splice(idx, 1);
correctAnswerArray.push(country);
}

console.log(correctAnswerArray);
console.log(res.data.length);
setCorrectAnswer(correctAnswerArray);
console.log(correctAnswer);
}
fetchData();
}, [])
useEffect(() => {
}, [currentQuestion])
return (
<div className='container'>
<div>
<div className='bg-white p-8 rounded shadow mb-4'>
<p className='text-2xl'>
What is the capital of COUNTRY_CORRECT ANSWER?
</p>
</div>
<div className='flex flex-wrap mt-4 justify-around'>
<button className='bg-white w-5/12 p-4 text-black font-semibold rounded shadow mb-4
transition duration-300 ease-in-out hover:scale-110'>
CHOICE 1
</button>
<button className='bg-white w-5/12 p-4 text-black font-semibold rounded shadow mb-4
transition duration-300 ease-in-out hover:scale-110'>
CHOICE 2
</button>
<button className='bg-white w-5/12 p-4 text-black font-semibold rounded shadow mb-4
transition duration-300 ease-in-out hover:scale-110'>
CHOICE 3
</button>
<button className='bg-white w-5/12 p-4 text-black font-semibold rounded shadow mb-4
transition duration-300 ease-in-out hover:scale-110'>
CHOICE 4
</button>
</div>
<p className='text-center text-xl'>{score} / 10</p>
</div>
</div>
)
}
export default Game;

我认为当使用var来存储和数组不反映状态的变化时,您必须在setState()中构建数组以便react注意到变化,例如这不能正常工作:

function lalaland () {
newArray = statedArray;
newArray[newArray.length] = "new Value";
setStatedArray(newArray);
}

但是如果你在setState中重建数组,现在react refresh:

function lalaland () {
newArray = statedArray;
newArray[newArray.length] = "new Value";
setStatedArray([...newArray]);
}

我很抱歉我的英语不好LOL

相关内容

  • 没有找到相关文章

最新更新