Redux-Form initial values from

前端 未结 6 1066
名媛妹妹
名媛妹妹 2020-12-08 09:16

I\'m trying to fill the profile form with data from API. Unfortunately redux-form doesn\'t want to cooperate with me in this case. For some reason fields stays empty whateve

6条回答
  •  伪装坚强ぢ
    2020-12-08 10:04

    initialize() is a prop provided by reduxForm, that can be used to fill up the form values.

    change() is another prop provided by reduxFrom to change a field value.

    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 {
    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 (
            
                
    { this.setState({ value: e.target.value }); change('firstName', e.target.value); }} />
    ); } } export default connect((state) => { return { session: state.session } }, {} )(withRouter((reduxForm({ form: 'contact' })(ContactForm))));

提交回复
热议问题