对表单进行了双向绑定却`setFieldsValue`失败

2018-10-15  本文已影响0人  广州芦苇科技web前端

作者:饶尧;
标签: react, ant design组件


需求

管理后台,点击编辑对应的条目之后,弹出修改框,希望弹出框中预设条目中原来的值


enter description hereenter description here

实现难点

对表单的输入框进行双向绑定之后使用setFieldsValue却只给了下面的赠送栏赋初始值,并且报错

Warning: Cannot use setFieldsValue until you use getFieldDecorator or getFieldProps to register it.

思路分析

思路一的代码实现

1.原始代码

{console.log("this.state.ruleType  "+this.state.ruleType)}
/**条件渲染*/
        {this.state.ruleType === 'CONSUMPTION' && (   
                        <FormItem {...formItemLayout} label="使用" >
                            {getFieldDecorator('ruleConsumptionType', {
                                rules: customRules,
                                // initialValue: this.state.ruleConsumptionType,
                            })(<Select style={{ width: 140 }} >
                                <Option value="BABY">娃娃机</Option>
                                <Option value="ARMCHAIRE">按摩椅</Option>
                            </Select>)}
                        </FormItem>
                )}
    handleRowEditClick = async (index, record) => {
        console.log(record)
        const {
            ruleConsumptionType,
            ruleCount,
        } = record

        this.setState({
            isShowEditModal: true,
            ruleType: ruleType,
        })
        this.props.form.setFieldsValue({
            ruleType: ruleType,  
            /* Tempate Form Item Field as Params */
            /* 并不能成功的设置初始值 */
        })
        console.log("this.state.ruleType")
        console.log(this.state.ruleType)
        console.log("this.props.form.ruleType")
        console.log(this.props.form.getFieldValue("ruleType"))
    };

2.修改后代码

设置一个标志位consumptionStyle,来控制盒子的显隐
style = {{display: this.state.consumptionStyle}}

  <div className = {styles.countItem} style = {{display: this.state.consumptionStyle}}>
  <FormItem {...formItemLayout} label="使用" >
                            {getFieldDecorator('ruleConsumptionType', {
                                rules: customRules,
                                // initialValue: this.state.ruleConsumptionType,
                            })(<Select style={{ width: 140 }} >
                                <Option value="BABY">娃娃机</Option>
                                <Option value="ARMCHAIRE">按摩椅</Option>
                            </Select>)}
                        </FormItem>
  </div>

注意事项

1.setState是异步的,设置后直接取state的值需要再回调函数里面去取,但是页面上的state就已经是更新成对应的值了
使用了setStatesetFieldsValue两种方式分别设置State和表当中名为ruleType输入框的值
setState是异步的所以显示为空,而表单中的不是

错误信息打印错误信息打印

2.在FormItem被隐藏时,输入框可能为空,这个时候就要对校验字段进行筛选,确定在什么情况下需要交验哪些字段,否则会导致校验不通过不能够提交表单

enter description hereenter description here

3.在写页面逻辑时用了很多的setStatesetFieldsValue适度选则,不要滥用,据说setState会影响页面性能,待商榷

上一篇 下一篇

猜你喜欢

热点阅读