Redux-Form 初始值来自

IT技术 reactjs redux react-redux redux-form
2021-04-04 17:54:24

我正在尝试使用来自 API 的数据填写个人资料表单。不幸的是,在这种情况下,redux-form 不想与我合作。出于某种原因,无论我做什么,字段都是空的。

由于某种原因,设置固定值而不是从减速器传递的值工作得很好。

也许这是因为我在动作创建者内部使用redux-promise进行 API 调用?我怎么能忍受它并摆脱它。这是我的表单组件。

import React, { Component } from 'react';
import { reduxForm, Field } from 'redux-form';
import { connect } from 'react-redux';
import { fetchRoleList, fetchUserData } from '../actions';

class UserEdit extends Component {

    componentWillMount() {
        this.props.fetchRoleList();
        this.props.fetchUserData();
    }

    handleEditProfileFormSubmit(formProps) {
        console.log(formProps);
    }

    getRoleOptions(selected_id) {
        if (!this.props.profile) {
            return <option>No data</option>;
        }

        return this.props.profile.roles.map(role => {
            return <option key={role.role_id} value={role.role_id}>{role.name}</option>;
        });
    }

    renderField(props) {
        const { input, placeholder, label, value, type, meta: { touched, error } } = props;
        return (
        <fieldset className={`form-group ${ (touched && error) ? 'has-error' : '' }`}>
            <label>{label}</label>
            <input className="form-control" {...input} type={type} placeholder={placeholder} />
            {touched && error && <div className="error">{error}</div>}
        </fieldset>
        );
    }

    renderSelect({ input, placeholder, options, label, type, meta: { touched, error } }) {
        return (
        <fieldset className={`form-group ${ (touched && error) ? 'has-error' : '' }`}>
            <label>{label}</label>
            <select className="form-control" {...input}>
                {options}
            </select>
            {touched && error && <div className="error">{error}</div>}
        </fieldset>
        );
    }

    render() {
        const { handleSubmit } = this.props;

        const user = this.props.profile.user;

        return (
        <div> {user ? user.email : ''}
            <form onSubmit={handleSubmit(this.handleEditProfileFormSubmit.bind(this))}>
                <Field name="email" label="Email:" component={this.renderField} type="text" placeholder="email@gmail.com" className="form-control"/>
                <Field name="name" label="Name:"  component={this.renderField} type="text" placeholder="John Doe" className="form-control"/>
                <Field name="role" label="Role:" component={this.renderSelect} type="select" className="form-control" options={this.getRoleOptions()}/>
                <button action="submit" className="btn btn-primary">Edit user</button>

                <Field name="password" label="Password:" component={this.renderField} type="password" className="form-control"/>
                <Field name="passwordConfirm" label="Confirm Password:" component={this.renderField} type="password" className="form-control"/>
                { this.props.errorMessage
                &&  <div className="alert alert-danger">
                        <strong>Oops!</strong> {this.props.errorMessage}
                    </div> }
                <button action="submit" className="btn btn-primary">Sign up!</button>
            </form>
        </div>
        );
    }

}

let InitializeFromStateForm = reduxForm({
    form: 'initializeFromState'
})(UserEdit);

InitializeFromStateForm = connect(
  state => ({
    profile: state.profile,
    initialValues: state.profile.user
  }),
  { fetchRoleList, fetchUserData }
)(InitializeFromStateForm);

export default InitializeFromStateForm;

我确实相信动作创建者也会很有用:

export function fetchUserData(user_id) {
    user_id = user_id ? user_id : '';

    const authorization = localStorage.getItem('token');
    const request = axios.get(`${ROOT_URL}/user/${user_id}`, {
      headers: { authorization }
    });

    return {
        type: FETCH_USER,
        payload: request
    };
}
6个回答

您需要添加enableReinitialize: true如下。

let InitializeFromStateForm = reduxForm({
    form: 'initializeFromState',
    enableReinitialize : true // this is needed!!
})(UserEdit)

如果您的 initialValues props更新,您的表单也会更新。

哦,伙计,但是那个文档花了几个小时:(
2021-05-24 17:54:24
我什至不会承认我今天为此浪费了多少时间。你肯定是英雄!
2021-05-27 17:54:24
伙计,我在这上面花了三个小时。谢谢!
2021-06-01 17:54:24
是的。有用。太奇怪了我没有在官方文档中找到它
2021-06-09 17:54:24
花了3个小时搜索。很难找到,但enableReinitialize : true完成了这项工作。感谢那。
2021-06-17 17:54:24

要设置initialValuesreduxreduxForm()装饰器之前应用装饰器很重要connect()如果装饰器的顺序颠倒,这些字段将不会从商店状态填充。

const FormDecoratedComponent = reduxForm(...)(Component)
const ConnectedAndFormDecoratedComponent = connect(...)(FormDecoratedComponent)

如果除了第一次设置值之外,每次状态改变时都需要重新填充表单,然后设置 enableReinitialize: true

这个答案中找到一个简单的例子

阅读官方文档和完整示例

在此处阅读有关此问题的信息

所以,你正在尝试:

  • 将 API 数据加载到表单中
  • 仅在加载时更新表单(又名。initialValues

虽然@FurkanO 可能会起作用,但我认为最好的方法是在获得所有异步数据后加载表单,您可以通过创建父组件/容器来实现:

UserEditLoader.jsx

componentDidMount() {
  // I think this one fits best for your case, otherwise just switch it to
  // componentDidUpdate
  apiCalls();
}
/* api methods here */
render() {
 const { profile } = this.props;
 return (
   {profile && <UserEdit profile={profile} />}
 );
} 

基本上你应该做的UserEditLoader是执行 API 函数并更新状态(如果 redux 连接,则更新状态)。每当配置文件变量不为空时(意味着您获得了预期的数据),然后UserEdit使用配置文件作为props挂载

initialize() 是 reduxForm 提供的一个 prop,可用于填充表单值。

change() 是 reduxFrom 提供的另一个属性,用于更改字段值。

import * as React from 'react';
import { Field, reduxForm } from 'redux-form';
import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom';

const submit = values => {
    // print the form values to the console
    console.log(values)
}

interface Props {
    history?: any;
    location?: any;
    session?: any;
    handleSubmit?: Function;
    initialize?: Function;
    change?: Function;
}

class ContactForm extends React.Component<Props, any> {
constructor(props, state) {
    super(props, state);
    this.state = {
        value: ''
    };
}

componentDidMount() {
    const { initialize, session, location } = this.props;

    console.log(location.pathname);

    if (session && session.user) {
        const values = {
            firstName: session.user.name,
            lastName: session.user.lastName,
            email: session.user.email
        };
        initialize(values);
    }
}

componentWillReceiveProps(nextProps) {
    const { initialize, session } = this.props;

    if (nextProps.session !== session) {
        if (nextProps.session && nextProps.session.user) {
            const values = {
                firstName: nextProps.session.user.name,
                lastName: nextProps.session.user.lastName,
                email: nextProps.session.user.email
            };
            initialize(values);
        } else {
            const values = {
                firstName: null,
                lastName: null,
                email: null
            };
            initialize(values);
        }
    }
}

render() {
    const { handleSubmit, change } = this.props;
    return (
        <React.Fragment>
            <form onSubmit={handleSubmit(submit)}>
                <div>
                    <label htmlFor="firstName">First Name</label>
                    <Field name="firstName" component="input" type="text" />
                </div>
                <div>
                    <label htmlFor="lastName">Last Name</label>
                    <Field name="lastName" component="input" type="text" />
                </div>
                <div>
                    <label htmlFor="email">Email</label>
                    <Field name="email" component="input" type="email" />
                </div>
                <button type="submit">Submit</button>
            </form>



            <input type="text" value={this.state.value}
                onChange={(e) => {
                    this.setState({ value: e.target.value });
                    change('firstName', e.target.value);
                }}
            />
        </React.Fragment>
    );
}
}

export default connect((state) => {
    return {
        session: state.session
    }
},
{}
)(withRouter((reduxForm({
    form: 'contact'
})(ContactForm))));

如果enableReinitialize : true技巧不起作用,您可以在initialValuesprops更改时更新每个字段

componentWillReceiveProps(nextProps) {
    const { change, initialValues } = this.props
    const values = nextProps.initialValues;

    if(initialValues !== values){
        for (var key in values) {
            if (values.hasOwnProperty(key)) {
                change(key,values[key]);
            }
        }
    }
}

我从未合作过,FieldsArray但我认为这在这里不起作用。