【问题标题】:Warning: Cannot update a component (`App`) while rendering a different component警告:渲染不同组件时无法更新组件(`App`)
【发布时间】:2021-09-08 07:30:56
【问题描述】:

我的 APP 组件中有一个名为 setScore( ) 的函数,它作为道具传递给我的 Popup 组件。我想根据弹出组件中的条件调用UpdateScore( ) 函数。但是,我也想根据条件调用 setScore( ) 方法,但它给了我上面列出的错误。

const Popup = ({user,correctLetters,wrongLetters,setPlayable,selectedWord, playAgain, currentQuestion, words, score, setScore, quitGame}) => {

    function UpdateScore() {

            if(!check){
                check = true;    
                setScore(score => (score + 1));               
            }    
    };

    if ((checkWin(correctLetters,wrongLetters,selectedWord) === 'win') && (currentQuestion < words.length -1)){
        UpdateScore();
    } 
    else if((checkWin(correctLetters,wrongLetters,selectedWord) === 'win') && (currentQuestion === words.length -1 )){
        UpdateScore();
    }

这不是完整的代码,但主要问题在于setState( ) 调用。我查看了其他帖子,他们通过将 setState 方法包装在 useEffect 中解决了这个问题,但随后它又给了我另一个错误

无法有条件地渲染 useEffects。

知道如何解决这个问题吗?

【问题讨论】:

  • 您在Popup 渲染中调用setScore。你不能那样做。如果您需要在变量更改时更新您的状态,请使用 useEffect hook

标签: javascript reactjs react-redux react-hooks


【解决方案1】:

可能以下工作:

const isWin =
  checkWin(correctLetters, wrongLetters, selectedWord) ===
    'win' &&
  currentQuestion <= words.length &&
  !check;
React.useEffect(() => {
  if (isWin) {
    check = true;
    setScore((score) => score + 1);
  }
}, [isWin, setScore]);

我确实看到了 check 的问题,并且感觉它应该在 useRef 中。

【讨论】:

  • 非常感谢,解决了!检查胜利后我需要渲染。
【解决方案2】:

问题是你在组件的主体中调用了UpdateScore(即调用setScore),这不是 React 的工作方式。如果你想在Popup第一次渲染时执行if...else if,可以这样使用useEffect钩子:

useEffect(() => {
    if ((checkWin(correctLetters,wrongLetters,selectedWord) === 'win') && (currentQuestion < words.length -1)){
        UpdateScore();
    } 
    else if((checkWin(correctLetters,wrongLetters,selectedWord) === 'win') && (currentQuestion === words.length -1 )){
        UpdateScore();
    }
}, [correctLetters, wrongLetters, selectedWord, currentQuestion, UpdateScore]);

实际上,每次correctLetters, wrongLetters, selectedWord, currentQuestion, UpdateScore 之一更改其值时都会触发此useEffect(但您需要将这些作为依赖项,否则您将收到“缺少依赖项”的警告)。

【讨论】:

  • 非常感谢您的回答。它解决了:)
  • @HaroonOmer 没问题。有一个很好的编码 =)
猜你喜欢
  • 1970-01-01
  • 2021-07-05
  • 2021-03-29
  • 2020-09-25
  • 2022-09-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-17
相关资源
最近更新 更多