React-Admin:如何发送已从 API 调用中自动填充的输入值?

React-Admin: How to send input values that have been auto filled from an API call?

我有一个输入 'A' 从 API 获取地址数据并根据该数据自动填充输入 'B' 'C' 和 'D',但是在填写完输入后,我尝试将该表单发送到我的后端,发送了那些自动填写的输入中的 none,只发送了输入 'A'。此外,如果我手动编辑任何输入(删除一个字符,添加一个 space,更改值),我编辑的输入将发送到我的后端。

我正在使用减速器来存储状态。我使用的输入都是普通的 react-admin TextInput 组件。

代码如下:

const AutoFill = () => {
  const [searching, setSearching] = useState(false);
  const [error, setError] = useState(false);
  const [stateData, setStateData] = useReducer(
    (state, newState) => ({ ...state, ...newState }),
    {
      cep: '      -   ',
      address: '',
      number: '',
      neighborhood: '',
      city: '',
      state: '',
    }
  );

  const FormControl = (event) => {
    const { name, value } = event.target;
    setStateData({ [name]: value });
  };

  const SearchControl = (event) => {
    const { name, value } = event.target;
    setStateData({ [name]: value });
    if (value && !value.includes('_')) {
      setSearching(true);
      setStateData({ state: '...' });
      setStateData({ city: '...' });
      setStateData({ neighborhood: '...' });
      setStateData({ address: '...' });
      cep(value.replace('-', '')).then(
        (result) => {
          setSearching(false);
          setError(false);
          setStateData({ state: result.state });
          setStateData({ city: result.city });
          setStateData({ neighborhood: result.neighborhood });
          setStateData({ address: result.street });
        },
        () => {
          setSearching(false);
          setError(true);
          setStateData({ state: '' });
          setStateData({ city: '' });
          setStateData({ neighborhood: '' });
          setStateData({ address: '' });
        }
      );
    }
  };

  return (
    <>
      <TextInput
        source="cep"
        error={error}
        value={stateData.cep}
        onChange={SearchControl}
      />
      <TextInput
        source="address"
        disabled={searching}
        value={stateData.address}
        onChange={FormControl}
      />
      <TextInput
        source="number"
        disabled={searching}
        value={stateData.number}
        onChange={FormControl}
      />
      <TextInput
        source="neighborhood"
        disabled={searching}
        value={stateData.neighborhood}
        onChange={FormControl}
      />
      <TextInput
        source="state"
        disabled={searching}
        value={stateData.state}
        onChange={FormControl}
      />
      <TextInput
        source="city"
        disabled={searching}
        value={stateData.city}
        onChange={FormControl}
      />
    </>
  );
};

export const Create = (props) => {
  return (
    <Create {...props}>
      <SimpleForm>
        <NumberInput label="Value" source="price" />
        <AutoFill />
        <RichTextInput label="Description" source="description" />
      </SimpleForm>
    </Create>
  );
};

请使用此代码。
-index.js 文件

import axios from "axios";

export const setInputValue = (data) => {
    return axios.get(`https://www.example.com/profile`)
        .then((response) => {
            return response.data;
        });
};

-component.js

 return setInputValue(value).then(() => {
           this.setState(() => ({
                loading: false
            }));
        });

...
render(){
return (
...
   <input type="text" onClick={e => this.onClick(e)} value={this.state.value}/>
..
)}
...
  • 反应-admin.php
...
public function setInputValue(value)
    {
        try {
            $user->set(value);
            return response()->json(["result" => "successfully!"]);
        } catch (\Exception $e) {
            return getErrorResponse($e);
        }
    }

您将需要使用 React Final Form 的 FormState 和 Form 解决方案。例如,将使用我的代码片段。

1) 获取表单值

    const formState = useFormState();
    const form = useForm();

    const {
        asset_system_parent_id: majorSystem,
        classification,
    } = formState.values;

2) 设置 useEffect 以观察表单域的变化:

    useEffect(() => {
        const setFluidEnd = async () => {
          DO SOMETHING!!!!!
        };

        if ('Fluid End Maintenance' === classification) {
            setFluidEnd();
        }
    }, [classification, form, notify]);

3) 使用form.change(+ form.batch 如果你需要更新多个输入)

    useEffect(() => {
        const setFluidEnd = async () => {
            await requestGetList('asset-systems', 'id', 'ASC', 500, {
                description: 'Fluid End',
                relationship: 'parent',
            })
                .then(res => {
                    form.change('asset_system_parent_id', res.data[0].id);
                })
                .catch(error => {
                    notify(`System Assets not found`, 'warning');
                });
        };

        if ('Fluid End Maintenance' === classification) {
            setFluidEnd();
        }
    }, [classification, form, notify]);

您可以在此处阅读有关 api 的更多信息:https://final-form.org/docs/final-form/types/FormApi