目前,我正在尝试构建一个功能,它可以完成以下工作:
import { FC, useState } from 'react';
export const HandOutCards: FC = () => {
const [count, setCounter] = useState(0);
function firstHandOut(counter: number) {
let maxLength = 7;
for (let i = 0; i < 10; i++) {
console.log(i);
if (i === (maxLength + counter)) {
break;
}
}
}
const counter = () => {
setCounter(count + 1);
firstHandOut(count);
};
return (
<button onClick={counter}>HandOut</button>
);
};
但是在代码段中,代码现在这样做了:
如何在第二次或第三次单击时只添加一个索引。
发布于 2021-06-25 10:54:08
您必须保存最后一个计数i,以防止每次从0开始循环。
如果要内联地输出前7个数字,则必须在console.log ()循环之后调用for。但是,您可以在循环中为最终输出提供一个字符串。(只有在逗号不是第一个循环的情况下,才能使用简单的三元运算符在逗号前面加上前缀)
工作示例:(简化为演示)
let counter = 0;
let last_count = 0;
let maxLength = 7;
function firstHandOut() {
let output = '';
for (let i = last_count + 1; i < 10; i++) {
output += (i != last_count + 1 ? ', ' : '') + i;
if ((i === (maxLength + counter))) {
last_count = i;
break;
}
}
console.log(output);
counter++;
}<button type="button" onclick="firstHandOut();">test</button>
发布于 2021-06-25 10:47:27
您每次都是从0开始值i。相反,您应该从count启动它。尝尝这个。
for (let i = count; i < 10; i++) {
console.log(i);
if ((i === (maxLength + counter))) {
break;
}
}发布于 2021-06-25 11:11:12
您可以维护一个极小的最大值数组。这会让你有条件的省下来。还保持状态的最小值。
const {useState} = React;
function Example() {
const [count, setCounter] = useState(0);
const [min, setMin] = useState(1);
const max = [7, 8, 9];
function firstHandOut() {
const arr = [];
// Check the min state and the value in
// the dictionary for this count
for (let i = min; i <= max[count]; i++) {
arr.push(i);
}
console.log(arr.join(''));
// Update the min state
setMin(max[count] + 1);
}
function counter() {
setCounter(count + 1);
firstHandOut(count);
};
return (
<button onClick={counter}>HandOut</button>
);
};
// Render it
ReactDOM.render(
<Example />,
document.getElementById("react")
);<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react"></div>
https://stackoverflow.com/questions/68129616
复制相似问题