简体   繁体   中英

Pass initialValue as prop to redux-form field

There are lots of documents for redux-form, but none so far have helped with my particular setup.

End goal story

I want to pre-fill a profile form, eventually allowing data to be changed and sent back via the API.

Progress so far...

I can get the form to be pre-filled with static values in the form.js file. The next step is to replace these static values with the fetched data for that profile. I have the data ready and available for the profile on the index, I now need to pass this to the form.js and replace the static initialValues . However, the way the form.js file is structured its not as obvious to me how to pass this "prop" onto the initialValues tag.

INDEX.JS

import React, { Component } from 'react';
import { Provider } from "react-redux";
import store from "./store";
import MyForm from "./form";
import { connect } from 'react-redux';
import { whenGapiReady } from 'util/gapiHelper';
import PropTypes from 'prop-types';
import { fetchProfile } from 'actions/PlayerProfile';

class UserProfilePage extends Component {
    constructor(props) {
        super(props);
    }

    static propTypes = {
        playerId: PropTypes.string
    }

    componentDidMount() {
        this.handleInitialize();
    }

    componentDidMount() {
        whenGapiReady(() => {
            const { fetchProfile } = this.props;
            const { playerId } = this.props.match.params;
            fetchProfile(playerId);
        });
    }

    componentDidUpdate(prevProps, prevState, snapshot) {
        if (this.props.hasOwnProperty('profile')) {
            if (this.props.profile.playerId !== prevProps.profile.playerId) {
                // We only really need to reload the player if the playerId has changed
            }
        }
    }

    render() {

        const { playerId } = this.props.match.params;
        const { profile } = this.props;

        if (!playerId) {
            return null;
        }

        return (

            <Provider store={store}>                           
                <MyForm fullName={profile.fullName} />
            </Provider>

        );
    }
}

const mapStateToProps = ({ playerProfile, settings }) => {
    const { loader, profile, profileError } = playerProfile;
    const { darkTheme } = settings;
    return { loader, profile, profileError, darkTheme };
};

export default connect(mapStateToProps, { fetchProfile })(UserProfilePage);

As you can see from above I am trying to pass the profile name here:

<MyForm fullName={profile.fullName} />

FORM.JS

import React, { Component } from 'react';
import { reduxForm, Field, FieldArray } from "redux-form";

const renderfirstName = ({ fields }) => (
  <div>
    <h3>Player Profile:</h3>
    {fields.map((playerProfile, index) => (
      <div>
        <Field name={playerProfile} key={index} component="input" />
      </div>
    ))}
    <button type="button" onClick={() => fields.push()}>Add more</button>
  </div>
);
const MyForm = ({ handleSubmit, fullName }) => (
  <form onSubmit={ handleSubmit } initialValues={{fullName: fullName}}>
    <FieldArray name="fullName" component={renderfirstName} />
    <button type="submit">Submit</button>
  </form>
);
export default reduxForm({

  form: "foo",
  enableReinitialize: true,
  onSubmit: values => {
    window.alert( "Submited: \n" + JSON.stringify( values, null, 2 ) );
  }
})( MyForm );

I tried adding the initialValues tag directly onto the <form> tag:

<form onSubmit={ handleSubmit } initialValues={{fullName: fullName}}>

But initially I had the initialValues in the export like this:

export default reduxForm({
  form: "foo",
  initialValues: {
    playerProfiles: ['Tom Rudge']
  },
  onSubmit: values => {
    window.alert( "Submited: \n" + JSON.stringify( values, null, 2 ) );
  }
})( MyForm );

With the initialValues set in the form.js export the form is pre-populated with the static value, its just getting that fetched value onto the form from its parent index that seems to be the issue. Any help appreciated.

Ok so managed to work it out, hopefully this will help somebody else - and so I can reference back if I need to

INDEX.JS

<Provider store={store}>                           
     <MyForm initialValues={{fullName:[profile.fullName]}} />
</Provider>

Pass the InitialValue at component level.

FORM.JS

  <form onSubmit={ handleSubmit }>
    <FieldArray name="fullName" component={renderfirstName} />
    <button type="submit">Submit</button>
  </form>

Remove any other initialValues at form level

For those looking for a solution that includes react-redux, you can pull from props in the following manner.

Using mapStateToProps , make sure to pass ownProps as the second argument. You can then return an initialValues object that links your props to your form names, like so

function mapStateToProps(state, ownProps) {
  return {
    initialValues: { formName: ownProps.propsValue }
  };
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM