根据 JSON 值将 JSON 组应用于 TextFields 或选择

Apply JSON groups to TextFields or Selects based on a JSON Value

我从 API 中提取了一堆 JSON 个组。每个组包含 1 个或多个 questions 个对象。我需要在 MUI TextField 或 Select 中将每个问题及其对应的 response 附加到 textField,这需要根据 QuestionType 值来决定。

下面是我如何尝试获取数据以显示到 TextField。 TextFields 正在填充 [object Object],就像现在一样。

const [questions, setQuestions] = useState("");

const fetchQuestions = async () => {
   setQuestions(
      await fetch(`/fiscalyears/FY2023/intakes/${params.id}/details/questions`)
            .then((response) => response.json())
   );
};

useEffect(() => {
   fetchQuestions();
}, []);

...

{questions["question_groups"]?.map((row) => (
   <TextField
      fullWidth
      multiline
      className="text-field"
      value={row?.questions || ""}
      variant="outlined"
      margin="normal"
      label={row["GroupName"]}
   />
))}

这是我的一个例子JSON。实际上,question_groups

中可能有 20 个组
{
   "question_groups": [
      {
         "GroupName": "DDD",
         "questions": [
            {
               "Question": "1. Do you need a drink?",
               "QuestionType": "Select",
               "Response": null,
               "Choices": [
                  "Yes",
                  "No"
               ]
            }
         ]
      },
      {
         "GroupName": "FED",
         "questions": [
            {
               "Question": "2. What do you want to drink?",
               "QuestionType": "Text",
               "Response": null,
               "Choices": [
               ]
            },
            {
              "Question": "3. Do you want something to eat?",
               "QuestionType": "Text",
               "Response": "I would like steak",
               "Choices": [
               ] 
            }
         ]
      }
   ],
}

如有任何帮助或建议,我们将不胜感激。

首先,将 questions 初始化为字符串没有意义。尝试一个对象。

const [questions, setQuestions] = useState({});

另外,不清楚您实际上是将 fetchQuestions 的结果分配给 questions;假设您通过一个电话就得到了所有需要的问题,我假设您使用 setQuestions(response.json()) 或类似的方法来完成此操作。

如果你控制了 JSON 结构,我会改变它,但假设你不能,那么,我将如何映射它们以在 Select 和 [=17] 之间交替=] 会是这样的:

const App = () => {
    //... assume you have a state called `questions`
    //populated with your JSON object
    
    //create a component for each type
    const TextQuestion = ({question}) => {
        return(
            <div>
                <TextField //with your question and any necessary props
                />
                <TextField //with your answer
                />
            </div>
        )
    }
    
    const SelectQuestion = ({question}) => {
        return (
            <div>
                <TextField //with your question text
                />
                <Select //with your answer options
                />
            </div>
        )
    }

    //map the array of question_groups, then map the array 
    //of questions in each group and return one of your
    //component types depending on the value of QuestionType

    const questionComps = questions["question_groups"].map((group, i) => {
        return group["questions"].map((question, i) => {
            return question["QuestionType"] === "Text" 
            ? <TextQuestion key={`${i}${question.Question}`} question={question}/>
            : <SelectQuestion key={`${i}${question.Question}`} question={question} />
        })
    })
    //render the collection of question components
    return (
        <div>{questionComps}</div>
    )
}