我的 JSON 对象由字符串类型的correct_answer和 incorrect_answers 组成,这是一个我想在 incorrect_answers 数组中推送正确答案的数组,修改后我希望这个 JSON 对象作为我使用 React 钩子创建的修改状态的初始值。我怎样才能做到这一点。
var css = "ma2 pa2 br-pill dim pointer grow hover w-20";
const Logic = (props) => {
const ques = props.questions;
const [count, setCount] = useState(0);
//const [ques, setQues] = useState(props.questions);
const [modified, setModified] = useState((ques) => () => {
for (var i = 0; i < ques.length; i++) {
ques[i].incorrect_answers.push(ques[i].correct_answer);
}
return ques;
});
return (
<div className="tc">
{modified.length !== 0 ? (
<div>
{modified[count].incorrect_answers.map((home) => (
<div>
<button className={css}>{home}</button>
</div>
))}
</div>
) : (
<h1>loading</h1>
)}
</div>
);
};
export default Logic;
我作为道具获得的 JSON 对象看起来像
{
> "response_code": 0,
> "results": [
> {
> "category": "Entertainment: Video Games",
> "type": "multiple",
> "difficulty": "medium",
> "question": "When was the original Star Wars: Battlefront II released?",
> "correct_answer": "October 31, 2005",
> "incorrect_answers": [
> "December 18, 2004",
> "November 21, 2006",
> "September 9, 2007"
> ]
> },
> {
> "category": "Entertainment: Japanese Anime & Manga",
> "type": "multiple",
> "difficulty": "medium",
> "question": "In Dragon Ball Z, who was the first character to go Super Saiyan 2?",
> "correct_answer": "Gohan",
> "incorrect_answers": [
> "Goku",
> "Vegeta",
> "Trunks"
> ]
> },
> {
> "category": "Science & Nature",
> "type": "multiple",
> "difficulty": "easy",
> "question": "The human heart has how many chambers?",
> "correct_answer": "4",
> "incorrect_answers": [
> "2",
> "6",
> "3"
> ]
> }
> }
您可以使用 useEffect hook 来操作数据并将其存储在 modified 中。
const [modified, setModified] = useState([]);
useEffect(() => {
setModified(props.questions.map(data=>({...data,incorrect_answers:data.incorrect_answers.concat([data.correct_answer])})));
}, [props.questions]);