由于返回数组的函数,我们如何在useState中设置初始状态?

时间:2020-06-26 07:29:04

标签: javascript json reactjs react-hooks

我的JSON对象由字符串类型的correct_answer和我要在correct_answers数组中推入正确答案的数组(不正确的数组)组成,并且在修改后,我希望将此JSON对象作为我们状态的初始值 modified 是我使用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"
>             ]
>         }
>          }

1 个答案:

答案 0 :(得分:0)

您可以使用useEffect挂钩来处理数据并将其存储在修改后的页面中。

const [modified, setModified] = useState([]);    
    useEffect(() => {
           setModified(props.questions.map(data=>({...data,incorrect_answers:data.incorrect_answers.concat([data.correct_answer])})));
         }, [props.questions]);
相关问题