使用场景:
编辑商品信息,编辑页面要带入商品的名称等信息
开始使用usestate和useEffect结果不行,会不停刷接口,或者usestate里面的值不更新,用的初始值,而不是接口返回值
以下是antd的官方表述表单 Form - Ant Design
-
你不能用控件的
value
或defaultValue
等属性来设置表单域的值,默认值可以用 Form 里的initialValues
来设置。注意initialValues
不能被setState
动态更新,你需要用setFieldsValue
来更新。 -
你不应该用
setState
,可以使用form.setFieldsValue
来动态改变表单值。
正确操作
//创建一个引用
const formRef = React.createRef()
//对引用赋值productName和productId是表单的name名称
function Edit(props) {
useEffect(()=>{
if(props.match.params.id){
getOneById(props.match.params.id).then(res=>{
console.log(res.data.content.productName)
formRef.current.setFieldsValue({
productName: res.data.content.productName,
productId:res.data.content.productId
})
})
}
},[]) }
//在表单中关联这个引用formRef
<Form ref={formRef} name="nest-messages" onFinish={onFinish}
onFinishFailed={onFinishFailed}>
{/* 此处与视频讲解不一样antd4已更新*/}
<Form.Item label="名字" rules={[{required:true ,message: 'name is required'},{warningOnly: true}]} name="productName" >
<Input placeholder="请输入商品名字" />
</Form.Item>
<Form.Item label="价格" rules={[{required:true,message: 'price is required'},{warningOnly: true},{validator:PriceValidate}]} name="productId">
<Input placeholder="商品价格" />
</Form.Item>
<Form.Item>
<Button htmlType="submit " type="primary">保存</Button>
</Form.Item>
</Form>