reactjs 我的React代码有时会崩溃,但不总是

x8diyxa7  于 2023-01-25  发布在  React
关注(0)|答案(1)|浏览(134)

我正在构建一个项目,其中只有一个问题,当按下刷新按钮时它会发生变化。一切都很顺利,但有时代码崩溃,页面变空(如所附图片)按下刷新按钮。

import React from "react"
import questionsData from '../questionsData.js'

function Content(){

    const [question, setQuestion] = React.useState({
        heading:"",
        hints : []
    })

    const [refresh, setRefresh] = React.useState(0)
    

    React.useEffect(function(){
        if(questionsData){
            const randomNo = Math.floor(Math.random() * questionsData.length) + 1
         
            let headinggg = questionsData[randomNo].heading
            let hintsss = questionsData[randomNo].hints
            setQuestion({
              heading: headinggg,
              hints: hintsss
            })
        }else{
           document.write("loading")
        }
        
         
    },[refresh])

  const sugg = question.hints.map((hint) => {
      return(
          <li>{hint}</li>
      )
  })

  function renderQuestion(){
        setRefresh(refresh + 1)
  }

    return(
            <div className="content">
                <div className="question">
                        <h4>{question.heading}</h4>
                        <br />
                        <span>You should say:</span> 
                        <ul>
                           {sugg} 
                        </ul>
                    </div>
                <div className="action">
                    <div className="record">
                        <img src="images/211859_mic_icon.svg" alt="" />
                    </div>
                    <div className="refresh" onClick={renderQuestion}>
                        <img src="images/3994399_refresh_reload_repeat_rotate_sync_icon.svg" alt="" />
                    </div>
                </div>
            </div>
    ) 
}

export default Content

yzuktlbb

yzuktlbb1#

您应该从randomNo计算中删除+ 1,否则可能会导致IndexOutOfBounds错误:

const randomNo = Math.floor(Math.random() * questionsData.length);

相关问题