我的 Formik 表单未从数据库填充数据

问题描述 投票:0回答:1

我的 Formik 表格有两个问题。第一个问题是群体选择。我正在调用我的数据库并获取包含正确数据的响应,但它没有显示在选择字段中。让我困惑的是,尽管我在文件中硬编码了性别,但填充性别没有问题。

第二个问题是福米克政府没有读懂教会领域。我将其禁用,因为它是根据登录 jwt 令牌的用户填充的。因此,当用户尝试创建成员并在错误的教会中创建他/她时,不会出现错误。

API调用


 useEffect(() => {
        console.log("useEffect is running");
      
        const fetchData = async () => {
          try {
            const groupResponse = await GroupService.allGroups();
            const churchResponse = await ChurchService.allChurches();

            if (groupResponse.$values && churchResponse.$values) {
                      // Map groups to the format expected by Select component
              const groups = groupResponse.$values.map(group => ({
                label: group.groupName,
                value: group.groupId.toString(),
              }));
              // setGroups(groupResponse.$values, ...Groups);
              setGroups(groups);
              setChurches(churchResponse.$values);
                // Log the groups data
        // console.log("Groups Data:", Groups);
      
              // Assuming you have a function to get the churchId from JWT token
              const tokenChurchId = getChurchId(); // Replace with the actual function
              console.log("Token ChurchId:", tokenChurchId);

              // Log the updated state after the state has been updated
            //   console.log("Updated Groups:", groupResponse.$values, ...Groups);
            //   console.log("Updated Churches:", churchResponse.$values);
            //   console.log("Updated ChurchId:", tokenChurchId);

            // Update the churchId state
          setChurchId(tokenChurchId);
  
            } else {
              console.error("Unexpected response format or API request failed");
            }
      
            // Rest of your code...
          } catch (error) {
            console.error("Error fetching data:", error);
            }
        };
        fetchData();
    }, []);
    



福米克形式



        <Formik 
        
            onSubmit={handleFormSubmit}
            initialValues={initialValues}
            validationSchema={memberSchema}
            >
                {({values,errors, touched, handleBlur, handleChange, handleSubmit})=>(
                    <form onSubmit={handleSubmit} className="createMember-form">
                        {console.log("Formik State:", values)}
                        <Box 
                            display="grid" 
                            gap="30px" 
                            gridTemplateColumns="repeat(4, minmax(0,1fr))"
                            sx={{
                                "& > div": {gridColumn: isNonMobile ? undefined : "span 4"}
                            }}
                        >
                            <TextField
                                fullWidth
                                variant="filled"
                                type="text"
                                label="First Name"
                                onBlur={handleBlur}
                                onChange={handleChange}
                                value={values.firstName}
                                name="firstName"
                                error={!!touched.firstName && !!errors.firstName}
                                helperText={touched.firstName && errors.firstName}
                                sx={{gridColumn: "span 2"}}
                            />
                            <TextField
                                fullWidth
                                variant="filled"
                                type="text"
                                label="Last Name"
                                onBlur={handleBlur}
                                onChange={handleChange}
                                value={values.lastName}
                                name="lastName"
                                error={!!touched.lastName && !!errors.lastName}
                                helperText={touched.lastName && errors.lastName}
                                sx={{gridColumn: "span 2"}}
                            />
                            <TextField fullWidth variant="filled" sx={{gridColumn: "span 2"}}
                                select
                                id="gender"
                                label="Gender"
                                onBlur={handleBlur}
                                onChange={handleChange}
                                value={values.gender ?? ""}
                                name="gender"
                                error={!!touched.gender && !!errors.gender}
                                helperText={touched.gender && errors.gender}
                                
                            >
                                {options.map((option)=>(
                                    <MenuItem key={option.id} value={option.value}>
                                        {option.label}
                                    </MenuItem>
                                ))}
                            </TextField>
                            <TextField fullWidth variant="filled" sx={{ gridColumn: "span 2" }}
                                select
                                id="group"
                                label="Group"
                                onBlur={handleBlur}
                                onChange={handleChange}
                                value={values.group ?? ""}
                                name="group"
                                error={!!touched.group && !!errors.group}
                                helperText={touched.group && errors.group}
                            >
                                {groups.map((group) => (
                                    <MenuItem key={group.groupId} value={group.groupId}>
                                        {group.groupName}
                                    </MenuItem>
                                ))}
                                {console.log("Current value of 'group':", values.group)}
                            </TextField>
                        <TextField 
                            fullWidth
                            variant="filled"
                            type="text"
                            label="Church"
                            onBlur={handleBlur}
                            onChange={handleChange}
                            value={getChurchNameById(churchId)}
                            name="church"
                            disabled
                            sx={{ gridColumn: "span 4" }}
                            />
                        </Box>
                        <Box display="flex" justifyContent="end" mt="20px" gap={2}>
                            <Button type="reset" color="secondary"> 
                                Reset
                            </Button>
                            <Button type="submit" color="secondary" variant="contained">
                                Create New Member
                            </Button>
                        </Box>
                    </form>
                )}
        </Formik>



reactjs textfield formik
1个回答
0
投票

好吧,我不知道这是否就是全部,但我确实发现了一些东西。 首先,在 Api 调用中您可以看到:

const groups = groupResponse.$values.map(group => ({
                label: group.groupName,
                value: group.groupId.toString(),
              }));
              // setGroups(groupResponse.$values, ...Groups);
              setGroups(groups);

但是当你渲染时,你会这样做:

{groups.map((group) => (
                         <MenuItem key={group.groupId} value={group.groupId}>
                                {group.groupName}
                         </MenuItem>
))}

因此,您将 groups 设置为具有标签和值的对象数组,但随后您再次使用 groups.groupId 和 groups.groupName,这在第一个代码运行后不应该存在。

其次,Formiuk 不读取禁用字段,这是预期的行为。因此,如果您仍然希望它出现在表单提交数据上,一种解决方案是以某种方式隐藏它,而不是禁用它。

© www.soinside.com 2019 - 2024. All rights reserved.