基于相关记录字段的React Admin Change字段

问题描述

比方说,我有一个名为“资产”的记录,其中有一个名为deducitble的列。资产可以有一个保险人。保险公司有一个布尔字段“ allowOtherDeductible”。

在编辑资产时,我希望能够首先检查关联的保险公司是否将allowOtherDeductible设置为true。如果是这样,我将为免赔额允许TextInput,如果为false,则为SelectInput。

我该如何实现?有条件渲染字段时,我看不到一种获取相关记录字段的方法

解决方法

我最终拉入了所有保险公司,并在加载组件时加载了资产。似乎效率不高,但我无法提出更好的方法:

export const AssetEdit = props => {
  const dataProvider = useDataProvider();
  const [insurers,setInsurers] = useState([]);
  const [asset,setAsset] = useState(null);
  const [otherDeductible,setOtherDeductible] = useState(false);

  useEffect(() => {
    dataProvider.getOne('assets',{ id: props.id })
    .then(({ data }) => {
      setAsset(data);
      return dataProvider.getList('insurers',{ pagination: { page: 1,perPage: 100 } });
    })
    .then(({ data }) => setInsurers(data))
    .catch(error => {
      console.log(error)
    })
  },[])

  useEffect(() => {
    if (asset && insurers) {
      const selectedInsurer = insurers.find(insurer => insurer.id === asset?.insurer_id);
      setOtherDeductible(selectedInsurer?.other_deductible);
    }
  },[insurers])

return (
    <Edit {...props}>
      <SimpleForm>
        {otherDeductible &&
        <NumberInput
          source={'deductible'}
          parse={val => dollarsToCents(val)}
          format={val => centsToDollars(val)}
        />
        }

        <FormDataConsumer>
          {({ formData,...rest }) => {
            if(!otherDeductible){
              return <SelectInput
                source="deductible"
                parse={val => dollarsToCents(val)}
                format={val => centsToDollars(val)}
                choices={getDeductibleChoices(formData.insured_value)}
              />
            }
          }}
        </FormDataConsumer>
      </SimpleForm>
    </Edit>
)
}
,

我会利用SimpleForm向其所有子级注入record的事实来编写自定义输入:

const DeductibleInput = ({ record }) => {
    if (!record) return null;
    const { data,loaded } = useGetOne('insurers',record.insured_id);
    if (!loaded) return null; // or a loader component
    return data.otherDeductible 
      ? <NumberInput
          source="deductible"
          parse={val => dollarsToCents(val)}
          format={val => centsToDollars(val)}
        />
      : <SelectInput
          source="deductible"
          parse={val => dollarsToCents(val)}
          format={val => centsToDollars(val)}
          choices={getDeductibleChoices(record.insured_value)}
         />
}