Arrays 在输入字段中输入一个数字后,检查该数字是否存在于列表中
我正在通过我的项目学习reactjs和ReactHooks 篮球比赛中每个球员的得分 我希望应用程序执行以下操作:Arrays 在输入字段中输入一个数字后,检查该数字是否存在于列表中,arrays,reactjs,object,react-hooks,use-state,Arrays,Reactjs,Object,React Hooks,Use State,我正在通过我的项目学习reactjs和ReactHooks 篮球比赛中每个球员的得分 我希望应用程序执行以下操作: 在输入字段中输入一个数字 检查该号码是否已经存在 如果是:根据单击的按钮,将1、2、3添加到totPoints 如果否:添加数字,并且and totPoints=1,或torPoints=2,或totPoints=3。取决于单击的按钮 2a) 2b)如果否:将数字相加,并选择和totPoints=1,或torPoints=2,或totPoints=3。取决于单击的按钮 我从yout
const [number, setNumber] = useState('');
const [totPoints, setTotPoints] = useState(0);
const [scorers, setScorers] = useState([
{id: nanoid(4), number: 9, totPoints: 99},
{id: nanoid(4), number: 1, totPoints: 11},
{id: nanoid(4), number: 15, totPoints: 9},
]);
const onePointScoredHandler = () => {
const players = [...scorers];
const existingScorer = players.find((player) => player.number === number);
if (existingScorer) {
console.log('exist');
} else {
console.log('new');
}
不幸的是,
if(existingScorer)
无法识别列表中已经存在的数字,但是console.log('new')
无论我在输入字段中输入什么数字,这是因为您的number
状态是一个字符串,而player.number
是一个数字。您可以使用+
将其转换为数字,以正确比较它们:
const existingScorer = players.find((player) => player.number === +number);
我想知道你是怎么定的。您输入的代码似乎正确。现在我想继续我的应用程序,如果existingScorer为true,我想用此代码添加玩家以前的总分
if(existingScorer){console.log('existingScorer');existingScorer.totPoints=setTotPoints((prevState)=>prevState+1);SetCorers(existingScorer);}
不幸的是,它不起作用:totPoints未定义&得到一个不可忽略的错误[