问题
I'm passing currentUser data from my Redux-saga into antd form, Name, email, phone number, introduction are passed to the form as initialvalue, what i want to do is i want to submit the form as a put request to db if the initialvalue has been changed.. here is my code
import React from 'react';
import {createStructuredSelector} from 'reselect';
import { connect } from 'react-redux';
import { selectCurrentUser } from '../../redux/user/user.selector';
import { Form, Input, Button } from 'antd';
import './profile_form.styles.css'
/* eslint-disable no-template-curly-in-string */
const ProfileForm = ({currentUser}) => {
const {name, email} = currentUser
const onFinish = values => {
console.log(values);
};
const layout = {
labelCol: {
span: 7,
},
wrapperCol: {
span: 15,
},
};
return (
<Form className='profile-form' {...layout}
onFinish={onFinish}
initialValues={{ firstname: name, lastname: name, email: email }}
>
<Form.Item
name='firstname'
label="First Name"
>
<Input />
</Form.Item>
<Form.Item
name= 'lastname'
label="Last Name"
>
<Input value={name}/>
</Form.Item>
<Form.Item
name='email'
label="Email"
>
<Input value={email} />
</Form.Item>
<Form.Item name= 'phonenumber' label="Phone Number"
>
<Input />
</Form.Item>
<Form.Item name='introduction' label="Introduction"
>
<Input.TextArea />
</Form.Item>
<Form.Item wrapperCol={{ ...layout.wrapperCol, offset: 8 }}>
<Button type="primary" htmlType="submit">
Submit
</Button>
</Form.Item>
</Form>
);
};
const mapStateToProps = createStructuredSelector({
currentUser:selectCurrentUser
})
export default connect(mapStateToProps) (ProfileForm);
i found "onValuesChange" in antd api but have no idea how it's to be used.
回答1:
If you are using hooks you can add an useEffect with the code:
useEffect(() => {
form.setFieldsValue(defaultValues)
}, [form, defaultValues])
Remember define the form value first:
const [form] = Form.useForm()
And remember to pass this form instance to the Form component:
<Form
form={form}
layout="vertical"
name="form-name"
initialValues={defaultValues}
onFinish={submitHandler}
>
In this form, you going to update the defaultValues when the component renders. If you are using classes, you can put the code inside componentDidUpdate lifecycle method.
Regards
回答2:
You can use componentdidupdate lifecycle method to compare the prev props and current props value to check whether the initial value is changed. If changed then make an api call to save in db. Hope this helps
来源:https://stackoverflow.com/questions/61422607/update-antd-form-if-initialvalue-is-changed