这是我的redux表单代码。我还将enableReinitialize
设置为true
并遵循react-form文档。
我已经对initialValues
对象进行了硬编码,仅用于测试目的。但我的表格仍未初始化。
import React, { Component } from 'react';
import { Container, Header, Body, Content, Title, Button, Text, Left, Icon, Right } from 'native-base';
import { Field, reduxForm } from 'redux-form';
import { connect } from 'react-redux';
import MyTextInput from './TextInput';
import { fetchProfileData } from '../../actions';
const validate = values => {
const error = {};
error.email = '';
error.name = '';
error.mobile = '';
let ema = values.email;
let nm = values.name;
let mob = values.mobile;
if (values.email === undefined) {
ema = '';
}
if (values.name === undefined) {
nm = '';
}
if (values.mobile === undefined) {
mob = '';
}
if (ema.length < 8 && ema !== '') {
error.email = 'too short';
}
if (!ema.includes('@') && ema !== '') {
error.email = '@ not included';
}
if (nm.length > 8) {
error.name = 'max 8 characters';
}
if (mob.length < 10 && mob !== '') {
error.mobile = 'min 10 digits';
}
return error;
};
class SimpleForm extends Component {
componentWillMount() {
this.props.fetchProfileData();
}
render() {
const { handleSubmit } = this.props;
console.log(this.props.initialValues);
return (
<Container>
<Header>
<Left>
<Button
transparent
onPress={() => this.props.navigation.navigate('DrawerOpen')}
>
<Icon name="menu" />
</Button>
</Left>
<Body>
<Title>Profile</Title>
</Body>
<Right />
</Header>
<Content padder>
<Field name='name' component={MyTextInput} label='Vendor Name' />
<Field name='company_name' component={MyTextInput} label='Company Name' />
<Field name='office_address' component={MyTextInput} label='Office Address' />
<Field name='email' component={MyTextInput} label='Email' />
<Field name='mobile' component={MyTextInput} label='Contact' />
<Button block primary onPress={handleSubmit((values) => console.log(values))} style={{ marginTop: 20 }}>
<Text>Save</Text>
</Button>
</Content>
</Container>
);
}
}
const mapStateToProps = state => {
return {
initialValues: { name: 'abcde@gmail.com' }
};
};
SimpleForm = connect(mapStateToProps, { fetchProfileData }
)(SimpleForm);
export default reduxForm({
form: 'test',
validate,
enableReinitialize: true
})(SimpleForm);
答案 0 :(得分:2)
我一直在努力解决这个问题。我从来没有能够获得任何道具工作。但我只需要一些初始状态,所以这对我有用。希望它也适合你。
-----如果您只想设置一次初始值,则此方法有效。
export default reduxForm({
form: 'test',
validate,
initialValues: { name: 'abcde@gmail.com' }
})(SimpleForm);
编辑:我似乎需要传入变量。这对我来说可以用于mapStateToProps中设置的变量。我认为你的设置不起作用,因为它将状态和道具映射到表单,然后添加reduxForm。看起来它需要反过来。
const mapStateToProps = (state) => {
return {
initialValues: {
name: 'foobar',
}
}
}
export default (connect(mapStateToProps, mapDispatchToProps)(reduxForm({
form: 'groupForm',
enableReinitialize: true
})(SimpleForm)))