我昨天开始学习 react,但在使用 useState 钩子时遇到了一些问题。我正在尝试做的事情:
我有一份挑战清单。每个挑战都包含一个初始轮(字符串)和下一轮(arr)。我试图在屏幕上显示initalRound,如果有任何nextRounds,请将它们作为记录插入到甲板中。每个 nextround 看起来像这样:[index (int), roundDescription (string).
实现此目的的 for each 循环。但是,之后我想删除第一个挑战,以便显示下一个挑战。但是,这不起作用,它使我在 {challenges[0]['initialRound']} 上出现对象未定义错误。如果我不使用 for each 循环,它确实按预期工作,但我没有得到我试图实现的相同 nextRound 格式。
我希望我的案例解释得足够清楚
import React, { useState } from 'react';
import { StyleSheet, View, Text, Button } from 'react-native';
import deck from './data/challenges'
const GameScreen = () => {
const [challenges, setChallenges] = useState(deck);
const popChallengeHandler = () => {
var currentChallenge = challenges[0]
var nextRounds = currentChallenge['nextRounds']
nextRounds.forEach(round => setChallenges((prevChallenges) => prevChallenges.splice(round[0],0,{
initialRound: round[1],
nextRounds: []
})))
setChallenges((prevChallenges) => prevChallenges.splice(1))
}
return (
<View>
<Text>{challenges[0]['initialRound']}</Text>
<Button onPress={popChallengeHandler} title="Next challenge" color="red"/>
</View>
);
}
export default GameScreen; ```