如何使用 Redux 表单预填充输入字段
How to pre-populate input field using Redux form
我一直在阅读有关使用一组初始值预填充表单的 Redux 表单 documentation,但是在该页面的示例中,单击按钮即可获取值,而我需要在页面加载时立即使用它们。
以下是我目前所拥有的。我可以在 render() 方法中接收初始值作为 props 就好了,但是我不确定如何将这些值传递给 Field 组件...
import React from 'react';
import { connect } from 'react-redux';
import { Field, reduxForm } from 'redux-form';
import { Redirect } from 'react-router-dom';
import requireAuth from '../components/hocs/requireAuth';
import { updateUserInfo } from '../actions/userActions';
class UserProfilePage extends React.Component {
renderField( field ) {
return(
<div className="input-wrap">
<label htmlFor={ field.name }>{ field.label }</label>
<input type="text" { ...field.input } />
</div>
);
}
render() {
console.log( 'Initial values', this.props.initialValues );
// Here's what this.props.initialValues looks like:
// {
// first_name: 'John',
// last_name: 'Doe'
// }
return (
<form>
<Field
label="Your first name"
name="first_name"
component={ this.renderField } />
</form>
);
}
}
UserProfilePage = connect(
state => ({
initialValues: state.currentUser.personal_info
})
)( UserProfilePage );
UserProfilePage = reduxForm({
form: 'UpdateProfileForm'
})( UserProfilePage );
export default requireAuth( UserProfilePage );
无论你要在哪里呈现 UserProfilePage,都将其作为 prop 传递,例如:
import UserProfilePage form 'path/to/UserProfilePage';
<UserProfilePage
{...otherProps}
initialValues={{first_name: user.first_name}}
/>
这样,当表单呈现名称为 first_name 的输入时,将具有传递的值
我一直在阅读有关使用一组初始值预填充表单的 Redux 表单 documentation,但是在该页面的示例中,单击按钮即可获取值,而我需要在页面加载时立即使用它们。
以下是我目前所拥有的。我可以在 render() 方法中接收初始值作为 props 就好了,但是我不确定如何将这些值传递给 Field 组件...
import React from 'react';
import { connect } from 'react-redux';
import { Field, reduxForm } from 'redux-form';
import { Redirect } from 'react-router-dom';
import requireAuth from '../components/hocs/requireAuth';
import { updateUserInfo } from '../actions/userActions';
class UserProfilePage extends React.Component {
renderField( field ) {
return(
<div className="input-wrap">
<label htmlFor={ field.name }>{ field.label }</label>
<input type="text" { ...field.input } />
</div>
);
}
render() {
console.log( 'Initial values', this.props.initialValues );
// Here's what this.props.initialValues looks like:
// {
// first_name: 'John',
// last_name: 'Doe'
// }
return (
<form>
<Field
label="Your first name"
name="first_name"
component={ this.renderField } />
</form>
);
}
}
UserProfilePage = connect(
state => ({
initialValues: state.currentUser.personal_info
})
)( UserProfilePage );
UserProfilePage = reduxForm({
form: 'UpdateProfileForm'
})( UserProfilePage );
export default requireAuth( UserProfilePage );
无论你要在哪里呈现 UserProfilePage,都将其作为 prop 传递,例如:
import UserProfilePage form 'path/to/UserProfilePage';
<UserProfilePage
{...otherProps}
initialValues={{first_name: user.first_name}}
/>
这样,当表单呈现名称为 first_name 的输入时,将具有传递的值