【问题标题】:Insert with React-Hook-Form使用 React-Hook-Form 插入
【发布时间】:2021-02-22 10:26:12
【问题描述】:

我有一个带有 React-Hook-Form 的模式,它将数据发送到我的 API 并将其保存在 MySql 数据库中,但是当我点击按钮时,只有 4 列被填充('id'、createdAt、updatedAt 和user_id),我还有更多 3 列('title'、'description'、'photo')。

export default function FeedModal() {
const [form, setForm] = useState([]);
const { register, handleSubmit, setValue } = useForm();
const [isModalVisible, setModalVisible] = useState(false);

useEffect(() => {
    register({ title: 'title' });
    register({ description: 'description' })
}, [register]);

const onSubmit = async ({ title, description, photo }) => {
    const data = { title, description, photo };
    await api.post('/posts/1/create')
        .then(response => setForm(response(data)))
        .then(JSON.stringify(form))
        .catch(console.error());
    return () => handleSubmit(onSubmit);
}

const toogleModal = () => {
    setModalVisible(!isModalVisible);
}

我的表格:

            <View style={styles.Card}>
                <View style={styles.pubCard}>
                    <Text style={styles.intro}>Criar publicação</Text>
                    <TextInput
                        value={form.title}
                        name={'title'}
                        ref={register({ required: true })}
                        onChangeText={text => setValue("title", text, { shouldValidate: true })}
                        multiline={true}
                        style={styles.titleInput}
                        placeholder="Titulo">
                    </TextInput>
                </View>

                <View style={styles.btnView}>
                    <TouchableOpacity style={styles.upload} title="Selecionar Foto" >
                        <Text style={{ color: 'white', fontFamily: 'Montserrat_400Regular', textAlign: 'center' }}>Selecionar Foto</Text>
                    </TouchableOpacity>
                </View>

                <KeyboardAvoidingView style={styles.descView}>
                    <TextInput
                        value={form.description}
                        name={"description"}
                        ref={register({ required: true })}
                        onChangeText={text => setValue("description", text)}
                        multiline={true}
                        style={styles.descInput}
                        placeholder="Nos descreva com detalhes sobre o caso do seu Pet"></TextInput>
                </KeyboardAvoidingView>
                <View style={styles.buttons}>
                    <TouchableOpacity onPress={toogleModal} style={styles.ButtonClose}><Text style={{ color: 'white', fontFamily: 'Montserrat_400Regular' }}>Fechar</Text></TouchableOpacity>
                    <TouchableOpacity onPress={handleSubmit(onSubmit)} style={styles.ButtonClose}><Text style={{ color: 'white', fontFamily: 'Montserrat_400Regular' }}> Criar</Text></TouchableOpacity>
                </View>
            </View>

【问题讨论】:

    标签: mysql react-native express sequelize.js react-hook-form


    【解决方案1】:

    也许useFieldArray 在这里使用会更好,因为您正在谈论插入。

    https://react-hook-form.com/api#useFieldArray

    然后您可以使用insert 操作。例如:

    import React from "react";
    import { useForm, useFieldArray } from "react-hook-form";
    
    function App() {
      const { register, control, handleSubmit, reset, trigger, setError } = useForm({
        // defaultValues: {}; you can populate the fields by this attribute 
      });
      const { fields, append, prepend, remove, swap, move, insert } = useFieldArray({
        control,
        name: "test"
      });
      
      return (
        <form onSubmit={handleSubmit(data => console.log(data))}>
          <ul>
            {fields.map((item, index) => (
              <li key={item.id}>
                <input
                  name={`test[${index}].firstName`}
                  ref={register()}
                  defaultValue={item.firstName} // make sure to set up defaultValue
                />
                <Controller
                  as={<input />}
                  name={`test[${index}].lastName`}
                  control={control}
                  defaultValue={item.lastName} // make sure to set up defaultValue
                />
                <button type="button" onClick={() => remove(index)}>Delete</button>
              </li>
            ))}
          </ul>
          <button
            type="button"
            onClick={() => insert(1, { firstName: "appendBill", lastName: "appendLuo" })}
          >
            append
          </button>
          <input type="submit" />
        </form>
      );
    }
    

    【讨论】:

      猜你喜欢
      • 2022-10-20
      • 2023-03-17
      • 2022-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-13
      • 2021-01-20
      • 2022-01-25
      相关资源
      最近更新 更多