Ant Design 表单设置值表单 props

Ant Design form set values form props

我在表单中使用 antd 设计。

在这里,我使用 shouldComponentUpdate 方法从 reducer profilereducer 设置值。

class ProfileForm extends Component {

 componentDidMount = () => {
  this.props.actions.getprofile()
 }

 shouldComponentUpdate = (nextProps) => {
  if (this.props.profile) {
   this.props.form.setFieldsValue({
    name: this.props.profile.name,
   });
  } else {
   this.props.form.setFieldsValue({
    firstname: 'loading',
   });
  }
 }


 render() {
  const { getFieldDecorator, getFieldValue } = this.props.form; 
     <Form layout="vertical">
        <FormItem label="First Name" >
            {getFieldDecorator('name', { rules: [{ required: true, message: 'Required!', }], })(
                <Input addonBefore={selectBefore} placeholder="First Name" />
            )}
        </FormItem>
    </Form>    
}


 function mapStateToProps(state) {
  return {
   profile: state.profilereducer.profile,
  }
 }

 function mapDispatchToProps(dispatch) {
  return {
   actions: bindActionCreators(actions, dispatch)
  }
 }

 const Profile = Form.create()(ProfileForm);

 export default connect(mapStateToProps, mapDispatchToProps)(Profile);
}

错误:

正如函数名所暗示的那样,shouldComponentUpdate 应该是 return 一个布尔值。如果应该调用 render()(这通常是默认值),则它应该 return true,如果不是,则应该为 false。它主要用作优化功能,开发人员可以在某些情况下跳过重新渲染组件。请参阅 react 文档,例如函数:https://reactjs.org/docs/react-component.html#shouldcomponentupdate

其次,我很清楚您为什么要在 profileform 之间进行重新映射。像这样直接在组件 类 内改变或更改属性通常被认为是一种反模式。您尝试将 profile 数据重新映射到 form 属性 是否有特殊原因?构造映射渲染函数并将其传递给那里的 <Form> 不是更简单吗?或者更好的是,让 reducer 从一开始就按照您希望的方式映射这些数据,而不必使用具有相似数据但结构不同的属性。

您在循环中设置状态,因此出现错误。这是处理它的更好方法..我只是将 selectBefore 作为变量(在您的代码中,我没有找到设置它)..如果出现错误,请将其更改为字符串..

componentDidMount = () => {
   this.props.actions.getprofile()
  }

  renderBasicform(initialVal) {
    const { getFieldDecorator, getFieldValue } = this.props.form;
    return (
      <Form layout="vertical">
        <FormItem label="First Name" >
          {getFieldDecorator('name', { initialValue: initialVal,rules: [{ required: true, message: 'Required!', }], })(
            <Input addonBefore={selectBefore} placeholder="First Name" />
          )}
        </FormItem>
      </Form>
    );
  }

  render() {
    if(!this.props.profile) {
        return (
          <div>
          {this.renderBasicform("Loading")}
          </div>
        );
    }

        return (
          <div>
            {this.renderBasicform(this.props.profile.name)}
            </div>
        );
  }