Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何将事件处理程序重复一定次数?_Javascript_Reactjs - Fatal编程技术网

Javascript 如何将事件处理程序重复一定次数?

Javascript 如何将事件处理程序重复一定次数?,javascript,reactjs,Javascript,Reactjs,这是我的密码 handleGenNums() { const genNum = Math.ceil(Math.random() * 70); if (this.state.nums.indexOf(genNum) === -1) { this.setState(() => { return { nums: this.state.nums.concat(genNum) }

这是我的密码

handleGenNums()
{
    const genNum = Math.ceil(Math.random() * 70);

    if (this.state.nums.indexOf(genNum) === -1)
    {
        this.setState(() => {
            return {
                nums: this.state.nums.concat(genNum)
            }
        });
     } 
     else
     {
        this.handleGenNums();
     }
}

// handlePlayLottery() {
//     while (this.state.nums.length <= 5) {
//         this.handleGenNums();
//     }
// }

我有一个按钮,可以在数组中插入一个数字。我想按一下按钮,但数组中有5个数字。我注释掉了我尝试的代码,因为它破坏了我的浏览器。任何帮助都将不胜感激

如果要根据某些条件调用事件处理程序一定次数,则只需使用: i阵列长度<5{ 这个.handleFunction; }

如果您想重复使用此功能,只需使用一个helper函数调用函数一定次数:

function callFunction(fn, n) {
  if (n <= 0) return;
  fn();
  callFunction(fn, --n);
}
函数调用函数fn,n{
如果n console.logtest,5;我将向您展示如何使用递归特性来实现这一点

handleGenNums(counter)
{
    // Check if we have to generate another number.

    if (counter <= 0)
        return;

    // Generate a random number.

    const genNum = Math.ceil(Math.random() * 70);

    // Check if the generated number already is in the array.
    // If number is not found, add the number, and call recursively
    // the method with counter decremented. If element exists, call
    // recursively again without decrementing the counter.

    if (this.state.nums.indexOf(genNum) === -1)
    {
        this.setState(() => {
            return {
                nums: this.state.nums.concat(genNum)
            }
        });

        this.handleGenNums(counter - 1);
     } 
     else
     {
        this.handleGenNums(counter);
     }
}

你能更透彻地解释一下你想要的是什么吗?我希望HandleGenums在点击按钮时运行5次,而不是一次。谢谢大家。我稍后会尝试一下。如果这是一个noob问题,很抱歉,但事实上,我是一个noob。我想我的解决方案可能是将每个数字作为一个单独的状态道具,而不是一个将它们添加到单个数组中。
handleGenNums(5);