繁体   English   中英

如何使用 useState 反应钩子创建嵌套的对象数组

[英]How to create nested array of objects using useState react hook

我在寻找有关如何使用 useState 挂钩填充空嵌套数组的解决方案时遇到问题。 我是一个反应初学者,我可能会错过一些东西。 在下面的步骤中,我将尝试总结问题。

1.)我收到这种数据格式作为道具 - {问题}:

{
  category: "General Knowledge"
  correct_answer: "Arby's"
  difficulty: "easy"
  incorrect_answers: (3) ['McDonald's', 'Burger King', 'Wendy's']
  question: "In which fast food chain can you order a Jamocha Shake?"
  type: "multiple"
}
  1. 我的目标 output 是用这个结构创建一个 object :
  value: "Opel",
  isClicked: false,
  isCorrect: true,
  incorrect_answers: [
    {isClicked: false, value: "Bugatti"},
    {isClicked: false, value: "Bentley},
    {etc...}
  ]
  1. 通过这种方法,我达到了结果,但我想找到一种更正确的反应方式。
useEffect(() => {

      const obj = {
        value: question.correct_answer, 
        isClicked: false, 
        isCorrect: true, 
        incorrect_answers: []
      }

      question.incorrect_answers.map((item) => 
      obj.incorrect_answers.push({
        value: item,
        isClicked: false,
      })
    )

    setAnswers(obj) 

    }, [])
  1. 我的目标是提到在 useState 中形成的数据结构,以及如何访问嵌套 arr 并用对象填充它的正确方法。

a) 我使用 useState 来设置 state 及其答案 obj 的数据结构。

 const [answers, setAnswers] = useState({
  value: question.correct_answer, 
  isClicked: false, 
  isCorrect: true, 
  incorrect_answers: [
    //I want multiple objects {value: '...', isClicked: ...},
    // Would be nice if I was able to insert objects in this a) step.
  ]
 })

b)也许在 useEffect 或其他一些函数上,我想用对象填充 incorect_answers 数组。

useEffect(() => { 

  // c) Im accesing the answers state and filling incorect_answers with obj

      setAnswers(prevState =>  { 
        return {
          ...prevState,
          incorrect_answers: [{
            value: question.incorrect_answers.map((item) => item),
            isClicked: false,
            isCorrect: false
          }]

        }
     
      })

 // d) my output:

/* {
  value: "Opel",
  isClicked: false,
  isCorrect: true,
  incorrect_answers: [
    {isClicked: false, value: [bugatti, bentley, bmw, citroen]},
  ]

} */
  

 }, [])

如果你使用map你不应该忽略它的响应,你不需要push送到数组

useEffect(() => {

  const obj = {
    value: question.correct_answer, 
    isClicked: false, 
    isCorrect: true, 
    incorrect_answers: question.incorrect_answers.map(item => ({ 
        value: item,
        isClicked: false
    }))
  }

  setAnswers(obj) 

}, [])

首次填充 state 时可以使用相同的方法

const [answers, setAnswers] = useState({
  value: question.correct_answer, 
  isClicked: false, 
  isCorrect: true, 
  incorrect_answers: question.incorrect_answers.map(item => ({ 
            value: item,
            isClicked: false
        }))
 })

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM