简体   繁体   English

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

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

I have an input 'A' that fetches address data from an API and auto fills inputs 'B' 'C' and 'D' based on that data, but after the inputs have been filled and I try to send that form to my backend, none of those auto filled inputs are sent, just the input 'A' is sent.我有一个输入“A”,它从 API 获取地址数据,并根据该数据自动填充输入“B”“C”和“D”,但在输入完成后,我尝试将该表单发送到我的后端,这些自动填充的输入均未发送,仅发送输入“A”。 Furthermore, if i manually edit any of the inputs (remove a char, add a space, change the value) the ones that I edited get sent to my backend.此外,如果我手动编辑任何输入(删除字符、添加空格、更改值),我编辑的输入会发送到我的后端。

I'm using a reducer to store the state.我正在使用减速器来存储 state。 The inputs that I'm using are all just normal react-admin TextInput components.我使用的输入都是普通的 react-admin TextInput 组件。

Here's the code:这是代码:

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>
  );
};

You're going to need to use React Final Form's FormState and Form solutions.您将需要使用 React Final Form 的 FormState 和 Form 解决方案。 Will use snippets of my code for example.例如,将使用我的代码片段。

1) Grab the form values 1) 获取表单值

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

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

2) Setup useEffect that will observe changes to a form field: 2) 设置 useEffect 来观察表单域的变化:

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

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

3) Use form.change (+ form.batch if you need to update multiple inputs) 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]);

You can read more about the api here: https://final-form.org/docs/final-form/types/FormApi您可以在此处阅读有关 api 的更多信息: https://final-form.org/docs/final-form/types/FormApi

Please use this code.请使用此代码。
-index.js file -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 -component.js

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM