reactjs 有没有办法只使用两个组件就可以从一个数组中更改另一个对象的属性,该数组是另一个对象的一部分,嵌套在React的数组中?

kt06eoxx  于 2023-01-08  发布在  React
关注(0)|答案(1)|浏览(146)

我试图更改单击事件的isSelected属性,但收到"无法读取未定义的属性"。此外,事件后的状态未定义。
下面是代码:

    • 应用程序js**
function App() {
  const [quiz, setQuiz] = React.useState(false)
  const [quizData, setQuizData] = React.useState([])
  
  React.useEffect(() => {
    async function getQuizData() {
      const res = await fetch("https://opentdb.com/api.php?amount=5&type=multiple")
      const data = await res.json()
      setQuizData(formatData(data.results))
    }
    getQuizData()
  }, [])
  
  function formatData(questions) {
    let formatedData = questions.map(item => {
      return {
        id: nanoid(),
        question: item.question,
        correctAnswer: item.correct_answer,
        answers: shuffleAnswers([...item.incorrect_answers, item.correct_answer])
      }
    })
    return formatedData
  }

  function shuffleAnswers(answers) {
    let randomAnswers = [...answers].sort((a, b) => Math.random() - 0.5)
    let randomAnswerList = randomAnswers.map(item => {
      return {
        id: nanoid(5),
        isSelected: false,
        option: item
      }
    })
    return randomAnswerList
  }

  function holdAnswer(id) {
    setQuizData(prevQuizData => prevQuizData.map(item => {
      item.answers.map(element => {
        if (element.id === id) {
          return {...element, isSelected: !element.isSelected}
        } else {
          return element
        }
      })
    }))
  }

  function startQuiz() {
    setQuiz(prevQuiz => !prevQuiz)
  }

  return (
    <main>
        { 
          quiz 
        ? 
        <div className='quiz-container'>
            <Quiz 
              quizData={quizData}
              handleClick={holdAnswer}
            />
        </div> 
        :
          <Start 
            handleClick={startQuiz} 
          /> 
        }
    </main>
  )
}
    • 测验. jsx**
function Quiz (props) {  
    console.log(props.quizData)  
    let allAnswers = props.quizData.map(item => {

        return (
            <div className="question-container">
                <h3 key={item.id} id={item.id} className="question-title">{item.question}</h3>
                <div className="question-answers">
                    {item.answers.map(element => {

                        const styles = {
                            backgroundColor: element.isSelected ? "#D6DBF5" : "white"
                        }

                        return (
                            <button 
                                id={element.id}
                                key={element.id}
                                style={styles}
                                onClick={() => props.handleClick(element.id)}
                            >
                                {element.option}
                            </button>
                        )
                    })}
                </div>
            </div>
        )
    })

    return allAnswers
}

格式化后的数据如下所示:

[
    {
        "id": "jB2iVcZ1qXqgdkvRS-dfH",
        "question": "When was the programming language &quot;C#&quot; released?",
        "correctAnswer": "2000",
        "answers": [
            {
                "id": "_RMiu",
                "isSelected": false,
                "option": "1998"
            },
            {
                "id": "MWrOT",
                "isSelected": false,
                "option": "1999"
            },
            {
                "id": "psITc",
                "isSelected": false,
                "option": "2001"
            },
            {
                "id": "I6Wp8",
                "isSelected": false,
                "option": "2000"
            }
        ]
    },
    {...and so on...}
]

我已经尝试了几种方法来改变setter函数的状态,但是我被卡住了,我不能继续这个项目。
下面是我尝试过的另一种方法,但结果是一样的:https://github.com/ktrebor/quizzical/tree/main/src

py49o6xq

py49o6xq1#

您没有使用item.answer.map()的结果,因此状态不会更新。

function holdAnswer(id) {
    setQuizData(prevQuizData => prevQuizData.map(item => ({
      ...item,
      answers: item.answers.map(element => {
        if (element.id === id) {
          return {...element, isSelected: !element.isSelected}
        } 
        
        return element
      })
   })))
  }

相关问题