在利用异步数据填充的组件上使用 initialValues

Use initialValues on component utilizing async data population

我正在尝试预填充个人信息,但我 运行 遇到了一个异步问题。任何帮助将不胜感激。

看过:https://medium.com/@1sherlynn/react-redux-form-two-ways-to-add-initial-values-ab48daa0a32e and https://redux-form.com/6.0.0-alpha.4/examples/initializefromstate/

class AccountOverview extends Component {

  constructor() {
    super();
    this.state = { data: [] };
  }

  async componentDidMount() {
    const data = { fullname: "fullname", username: "username" }

    this.setState({ data })

  }

  render() {
     console.log(this.state.data)

     <PersonalInfo
     initialValues={this.state.data} />

     ....

我希望表单由数据状态填充。我和他一起记录了以下结果

[]
{ fullname: "fullname", username: "username" }

我觉得异步调用完成后组件没有重新加载。

PersonalInfo.js:

const PersonalInfo = props => {

const { username, fullname, handleOnChange, validationErrors } = props;

return (
    <div>
    <h1> Personal Information</h1>
    <br />
    <Field
        type="text"
        name="fullname"
        icon=""
        label="Fullname"
        value={fullname}
        component={FormField}
        onChange={handleOnChange}
    />
    <Field
        type="text"
        name="username"
        icon=""
        label="Username"
        value={username}
        component={FormField}
        onChange={handleOnChange}
    />
    </div>
)

}

function mapStateToProps(state) {

return {
    state
   };

}

export default reduxForm({form: "AccountOverview"})(connect(mapStateToProps)(PersonalInfo))

docs开始,您错过了重要的一步。

Add initialValuesprop in mapStateToProps and you can retrieve initialValues from the redux store

所以你的 mapStateToProps 应该是,

const mapStateToProps = (state, props) => ({
  initialValues: state, // retrieve data from redux store 
})

To pass the initialValues props into the redux form, we use the connect function

Add enableReinitialize : true When set to true, the form will reinitialize every time the initialValues prop changes

这个,

export default reduxForm({form: "AccountOverview"})(connect(mapStateToProps)(PersonalInfo))

应该是,

export default connect(
  mapStateToProps
)(reduxForm({
   form: 'AccountOverview', // a unique identifier for this form
  enableReinitialize: true
})(PersonalInfo))