简体   繁体   中英

access to nested objects and arrays React

const [data, setData] = useState({
    questionText: "",
    answerOptions: [
      { answerText: "", isCorrect: "" },
      { answerText: "", isCorrect: "" },
      { answerText: "", isCorrect: "" },
      { answerText: "", isCorrect: "" },
    ],
  });

How can I change the value of answerText or isCorrect in onChange of input tag?

<input
        type="text"
       
        onChange={(event) =>
          setData({ ...data, answerText: event.target.value })
        }
      />

Since your answerOptions is an array so you need to follow the same spread operator for the array also.

 data = { questionText: "", answerOptions: [ { answerText: "", isCorrect: "" }, { answerText: "", isCorrect: "" }, { answerText: "", isCorrect: "" }, { answerText: "", isCorrect: "" }, ], } console.log({...data, answerOptions: [...data.answerOptions, {answerText: 'something', isCorrect: "some value"}]})

The above code will add a new object to an existing array. If you want to edit the existing object, I would suggest using a unique identifier to find out the object and update it using .map()

 data = { questionText: "", answerOptions: [ { answerText: "", isCorrect: "", id: 1 }, { answerText: "", isCorrect: "", id: 2 }, { answerText: "", isCorrect: "", id: 3 }, { answerText: "", isCorrect: "", id: 4 }, ], } console.log({...data, answerOptions: [...data.answerOptions.map(element => element.id == 2? {...element, answerText: 'updated text' }: element)] })

You can try the same logic in you react app and update your state variable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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