Redux-form:如何在模式弹出时从 API 调用加载值(编辑模式)到表单?

Nee*_*raj 0 html javascript reactjs redux redux-form

我对 React 和 Redux-Form 还很陌生,目前我需要一些帮助。

基本上我有列表页面和他们的编辑按钮。单击编辑时,我会显示一个带有字段的模式弹出窗口,并执行 API 调用以获取相应的列表数据。

您能否让我知道如何使用从 API 调用接收到的数据预先填充模态弹出窗口中的字段?

非常感谢带有代码示例的演示(就像我说我对 React & Redux & Redux-form 很陌生)。:(

提前致谢!

Sac*_*han 5

这是流程:

componentDidMount() {
    this.props.loadClient(); // dispatch an action from your component
}
Run Code Online (Sandbox Code Playgroud)

动作调度器

loadClient() {
 // API call here
}
Run Code Online (Sandbox Code Playgroud)

将结果存储在 redux reducer 中

case LOAD_PROFILE_SUCCESS:
  return {
    ...state,
    data: action.result // save your data here
  };
Run Code Online (Sandbox Code Playgroud)

然后将 initialValues 道具添加到 @connect 装饰器

@connect(state => ({
    initialValues: state.profile.data // load the saved data here
  }),
  { loadClient }
)
Run Code Online (Sandbox Code Playgroud)

示例:您可以在 reduxForm 本身加载初始值。

let AddUser = props => {
    const { handleSubmit, initialValues } = props;
    return (
        <form onSubmit={handleSubmit}>
            <div>
                <label htmlFor="name">Name</label>
                <Field name="name" component="input" type="text" />
            </div>
            <div>
                <label htmlFor="email">Email</label>
                <Field name="email" component="input" type="email" />
            </div>
            <div>
                <label htmlFor="phoneno">PhoneNo</label>
                <Field name="phoneNo" component="input" type="text" />
            </div>
            <button type="submit">Submit</button>
        </form>
    );
}

export default AddUser = reduxForm({ form: 'addUser', initialValues: {
  name: "abc",
  email: "abc@gmail.com",
  phoneNo: "1234567890"
} })(AddUser)
Run Code Online (Sandbox Code Playgroud)

您的组件必须具有 Form 组件。休息将由 redux-form 处理。

注意:
initialValues 的结构必须与表单数据相同。字段名称和对象属性名称应该相同。

有关更多详细信息,您可以参考 redux-form 官方页面这里