重新渲染过多。 React限制了渲染次数以防止无限循环。 React Hook和ReactJS

时间:2019-10-18 13:59:18

标签: javascript reactjs

试图获取当前字母数组并且还希望删除重复的字母,并且每次不匹配字母的长度达到5时,游戏结束了。信息,这应该是ReactJS中的挂机游戏。获取数组并尝试删除数组中的重复项对我来说并不重要,但是如何在不出现此错误的情况下将其存储在useState中。

向下滚动代码并检查: setRemoveDuplicate(noDuplicates);

import React, { useState, useEffect, useRef } from 'react';
import axios from 'axios';
import 'babel-polyfill';
import { connect } from 'react-redux';
import { store } from '../index.js';
import { newArray } from '../actions/index';
// import { isRegExp } from 'util';

const App = ({ filteredArray }) => {
    const [ guessed, setGuessed ] = useState([]);
    const [ word, setWord ] = useState("");
    const [ data, setData ] = useState([]);
    const [ count, setCount ] = useState(0);
    const [ arrayCount, setArrayCount ] = useState(0);
    const [ removeDuplicate, setRemoveDuplicate ] = useState([]);

    useEffect(() => {
        const runEffect = async () => {
            const result = await axios('src/api/api.js');
            setData(result.data);
        }
        runEffect();
    }, []);

    const randomWord = () => {
        setArrayCount(arrayCount + 1);
        if((arrayCount >= data.length - 1)) {
            setArrayCount(0);
            shuffle(data);
        } 
        replaceLetter(data[arrayCount].word);
        cleanWord();
    }

    const shuffle = (a) => {
        // create copy or new array
        
        let newArr = [...a];
        for (let i = a.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [newArr[i], newArr[j]] = [newArr[j], newArr[i]];
        }
        setData(newArr);
    }

    const replaceLetter = (string) => {
        let getString = string;
        setWord(getString);
    }

    useEffect(() => {
        const checkLetter = (event) => {
            let letter = String.fromCharCode(event.keyCode).toLowerCase();
        
            if(event.keyCode >= 65 && event.keyCode <= 90) {
                setGuessed((prev => [...prev, letter]));
            }

            if(event.keyCode === 13) {
                checkScore();
            }
        }
    
        document.addEventListener('keydown', checkLetter);

        return () => {
            document.removeEventListener('keydown', checkLetter);
        }
    }, [guessed, count]);  


    // check the part of the code here.....
    let newArray = guessed.filter(el=> word.indexOf(el) === -1); // filtering out the unmatched letters is ok
    let noDuplicates = Array.from(new Set(newArray)); // removing duplicated letters is also not an issue. 
    setRemoveDuplicate(noDuplicates); // there error starts when I want to add useState here

    const revealMatchedWord = (string, guessed = []) => {

        if(string.length > 0) {
            const regExpr = new RegExp(`[^${guessed.join("")}\\s]`, 'ig');
            return string.replace(regExpr, '_');    
        }
    }

    const curr = revealMatchedWord(word, guessed);
    const isGuessed = curr === word; // check if word is guessed.
                                               
    const cleanWord = () => {
        if(isGuessed) {
            setGuessed([]);
        }
        // setWrongLetter(0);
    }

    const checkScore = () => {
        let newScore = Math.round(((1000 / (count / curr.length)) * 20) / 100);
        setCount(0);
    }

    return (
        <div>
            <p></p>
            <p>{word}</p>
            <p>{revealMatchedWord(word, guessed)}</p>
            <button onClick={randomWord}></button>
        </div>
    )
}

const mapDispatchToProps = dispatch => ({
    newArray: (removeDuplicates) => dispatch(newArray(removeDuplicates))
});

const mapStateToProps = state => {
    return {
        filteredArray: state.game.filterArray
    }
};

export default connect(mapStateToProps, mapDispatchToProps)(App);

1 个答案:

答案 0 :(得分:0)

您可以尝试设置效果中的非重复项:

  useEffect(() => {
    setRemoveDuplicate(
      Array.from(
        new Set(
          guessed.filter(el => word.indexOf(el) === -1)
        )
      )
    );
  }, [guessed, word]);