我正在react中使用mui和formik创建一个表单。在使用 select 时,我使用 api 中的对象设置默认值,但 select 无法正常工作。我无法选择值,默认情况下也不会选择默认值。下面是代码:
import { Box, Button, FormControl, InputLabel, Select, TextField } from "@mui/material";
import React, { useEffect, useState } from "react";
import { useLocation, useParams } from "react-router-dom";
import { Formik } from "formik";
import * as yup from "yup";
import useMediaQuery from "@mui/material/useMediaQuery";
import Header from "../../components/Header";
import useAuth from "../../hooks/useAuth";
import axios from "axios";
import { MenuItem } from "react-pro-sidebar";
const EditEmployee = () => {
const { user_id } = useParams(); // employee id
const [emp, setEmployee] = useState({});
const [Companies, setCompanies] = useState([]);
const [defcompany, setDefcompany] = useState("");
const [CompanyId, setCompanyId] = useState(null);
const handleChange = (event) => {
setDefcompany(event.target.value);
};
const { auth } = useAuth();
// get companies
const GetCompanies = () => {
axios.get(`${process.env.REACT_APP_MAIN_API_URL}/companies/`).then(function (res) {
try {
var result = res.data;
// console.log(result);
setCompanies(result);
} catch (error) {
console.log(error);
}
});
};
useEffect(() => {
GetCompanies();
}, []);
// get companies
useEffect(() => {
try {
const response = axios
.get(`${process.env.REACT_APP_MAIN_API_URL}/employees/` + user_id, {
headers: {
"Content-Type": "application/json",
// Authorization: "Bearer " + auth.accessToken
},
// withCredentials: true,
})
.then((response) => {
setEmployee(response.data[0]);
setCompanyId(emp.company_id);
console.log(response.data[0]);
});
} catch (err) {
console.log(err);
if (!err?.response) {
console.log("No server Response");
} else if (!err?.response?.status === 400) {
console.log("Missing username or password");
} else if (!err?.response?.status === 401) {
console.log("Unauthorized");
} else {
console.log("Login Failed");
}
}
}, []);
const phoneRegExp = /^((\+[1-9]{1,4}[ -]?)|(\([0-9]{2,3}\)[ -]?)|([0-9]{2,4})[ -]?)*?[0-9]{3,4}[ -]?[0-9]{3,4}$/;
const userSchema = yup.object().shape({
first_name: yup.string().required("required"),
last_name: yup.string().required("required"),
email: yup.string().email("Invalid email").required("required"),
contact_no: yup.string().matches(phoneRegExp, "Phone number is not valid").required("required"),
// address1: yup.string().required("required"),
// address2: yup.string().required("required"),
});
const isNonMobile = useMediaQuery("(min-width:600px)");
const handleFormSubmit = (values) => {
console.log("VALUES");
console.log(values);
};
return (
{({ values, errors, touched, handleChange, handleBlur, handleSubmit, isSubmitting }) => (
)}
);
};
export default EditEmployee;
此外,我觉得选择的样式也存在一些问题。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
所以我得到了错误。我正在使用 React Pro 侧边栏的 MenuItem
我应该使用 mui 包中的 MenuItem