简体   繁体   English

React Native State 未使用空数组进行更新

[英]React Native State not updating with an empty Array

Hi stackoverflow people I know this has been asked about a million times.嗨 stackoverflow 人我知道这已经被问了大约一百万次。 However I don't think I have found an answer to my problem!但是,我认为我没有找到问题的答案!

Long story short I am updating a state in my react native app only if a statement is true.长话短说,仅当声明为真时,我才会在我的 react 本机应用程序中更新 state。 What I am experiencing is this state not being updated somehow.我遇到的是这个 state 没有以某种方式更新。

const emptyArray = []
const [collapsed, setCollapsed] = useState(true);
const [selectedGem, setSelectedGem] = useState(false);
const [usedGem, setUsedGem] = useState(emptyArray);
const [selectedPropType, setSelectedPropType] = useState('all');

const randomItem = (items) => {
    return items[Math.floor(Math.random()*items.length)];
}

const getRandomQuestion = () => {
    let selectableGems = gems

    const maxGems = selectableGems.length;
    let tempGems = [];

    if(usedGem.length >= maxGems) {
        setUsedGem(emptyArray)
    }

    for (let i=0; i<maxGems; i++)
    {
        if(usedGem.length === 0 || usedGem.find(gem => gem === i) === undefined) {
            tempGems.push(i)
        }
    }

    const randomGemNumber = randomItem(tempGems)

    setUsedGem([...usedGem, randomGemNumber])

    setSelectedGem(selectableGems[randomGemNumber])
}

Basically if(usedGem.length >= maxGems) { happens only when all the gems have been randomised once (there are 130 item in the gems variable).基本上if(usedGem.length >= maxGems) {仅在所有宝石都被随机化一次时发生( gems变量中有 130 个项目)。 I'd expect then the usedGem to be empty in the for but this isn't the case.我希望usedGemfor中为空,但事实并非如此。

I have tried a few solutions I found without luck.我尝试了一些没有运气的解决方案。 I know this has to do with async but I can't figure it out?我知道这与异步有关,但我想不通? Anyone could help me please?任何人都可以帮助我吗?

Here this might help.在这里,这可能会有所帮助。 The thing is you can't get instant update after setting state问题是设置 state 后您无法获得即时更新

const getRandomQuestion = () => {
let selectableGems = gems

const maxGems = selectableGems.length;
let tempGems = [];
let gems = Array.from(usedGem);

if(gems.length >= maxGems) {
    gems = []
}

for (let i=0; i<maxGems; i++)
{
    if(gems.length === 0 || gems.find(gem => gem === i) === undefined) {
        tempGems.push(i)
    }
}

const randomGemNumber = randomItem(tempGems)

setUsedGem([...gems, randomGemNumber])

setSelectedGem(selectableGems[randomGemNumber])
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM