将 JSON 对象设置为 material UI Select 组件 React Hooks 上的 Const

Set JSON object to a Const on material UI Select component React Hooks

我从 API 调用中得到一个 JSON 对象数组,分别是:

[
   {
      "staffTypeID":103,
      "staffType":"3",
      "staffPermissionType":"Regular",
      "staffRoleID":31,
      "staffRole":"Sales_Regular"
   },
   {
      "staffTypeID":52,
      "staffType":"1",
      "staffPermissionType":"Admin",
      "staffRoleID":11,
      "staffRole":"Admin"
   }
]

我正在使用Formik Material UI 将其列在Select 上,代码如下:

<Field name="StaffType" label="Staff Type"  component={Select}
                                       options={Object.keys(StaffTypes).map((StaffType) =>
({value: StaffTypes[StaffTypes].staffTypeID, label: StaffTypes[StaffTypes].staffRole}))}/>

我还有一个常量可以赋值:

const [staff,setStaff]=useState('');

我需要通过在下拉列表中选择,将 json 对象的值设置为人员常量。通过单击 Select 下拉菜单,员工常量应分配给

 {
    "staffTypeID":103,
    "staffType":"3",
    "staffPermissionType":"Regular",
    "staffRoleID":31,
    "staffRole":"Sales_Regular"
 }

所以我可以将其他代码用作 <h2>{staff.staffPermissionType.toUpperCase()}</h2>

谁能帮我解决这个问题。

我不熟悉 Formik,但我认为您在 this code sandbox.

上可以做到

Formik 组件向子组件提供当前表单值,因此您根本不需要 useState。

相关部分如下:

import React from "react";
import { Formik, Form, Field } from "formik";
import { Select } from "material-ui-formik-components/Select";

const StaffTypes = [
  {
    staffTypeID: 103,
    staffType: "3",
    staffPermissionType: "Regular",
    staffRoleID: 31,
    staffRole: "Sales_Regular"
  },
  {
    staffTypeID: 52,
    staffType: "1",
    staffPermissionType: "Admin",
    staffRoleID: 11,
    staffRole: "Admin"
  }
];

const FormCmp = ({ values, handleChange }) => {
  // get the currently selected StaffType id
  const staffRoleID = (values || {}).StaffType;

  // look up the item in the options array
  const staffType = StaffTypes.find(x => x.staffRoleID === staffRoleID);

  return (
    <div>
      {/* display the selected staffRole */}
      <h1>{staffType && staffType.staffRole}</h1>
      <Form>
        <Field
          name="StaffType"
          label="Staff Type"
          options={StaffTypes.map(entry => ({
            value: entry.staffRoleID,
            label: entry.staffRole
          }))}
          component={Select}
        />
      </Form>
    </div>
  );
};

function StaffTypeForm() {
  return (
    <div>
      <Formik initialValues={{ StaffType: StaffTypes[0].staffRoleID }}>
        {FormCmp}
      </Formik>
    </div>
  );
}

export default StaffTypeForm;