reactjs - redux-form 无法在字段中输入值

标签 reactjs react-redux redux-form

我无法使用 redux-form 在输入字段中键入值。我有以下 reducer

import {combineReducers} from 'redux';
import session from './sessionReducer';
import profile from './profileReducer';
import map from './mapReducer';
import { reducer as formReducer } from 'redux-form'

const rootReducer = combineReducers({
    // short hand property names
    session,
    profile,
    map,
    form: formReducer
})

export default rootReducer;

这里是商店

import { createStore, combineReducers, applyMiddleware } from 'redux'
import createLogger from 'redux-logger'
import thunk from 'redux-thunk'
import { routerReducer, routerMiddleware, push } from 'react-router-redux'
import reducers from '../reducers'
import { browserHistory } from 'react-router';

const middleware = [ thunk ];
if (process.env.NODE_ENV !== 'production') {
    middleware.push(createLogger());
}

middleware.push(routerMiddleware(browserHistory));


// Add the reducer to your store on the `routing` key
const store = createStore(
    combineReducers({
        reducers,
        routing: routerReducer
    }),
    applyMiddleware(...middleware),

)

export default store;

组件

import React, {PropTypes, Component} from 'react';
import Upload from './Upload';
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';
import * as profileActions from '../../../actions/profileActions';
import EventsCalendar from '../../common/EventsCalendar';
import { Field, reduxForm } from 'redux-form'
import ProfileForm from './ProfileForm';

import {
    Form,
    FormGroup,
    FormControl,
    ControlLabel,
    Tabs,
    Tab,
    InputGroup,
    Label,
    HelpBlock,
    Grid,
    Row,
    Button,
    Col

} from 'react-bootstrap';


class Profile extends Component {

    static propTypes = {
        profile: PropTypes.object.isRequired,
    };

    constructor(props) {
        super(props);

        this.state = {
            profile: {
                username: '',
                password: '',
                email: ''
            }
        }
        //this.onUpdate = this.onUpdate.bind(this)
    }

    handleSubmit = (values) => {
        // Do something with the form values
        console.log(values);
    }

    componentDidMount() {
        this.props.actions.getProfile()
    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.profile !== this.props.profile) {

        }
    }

    render() {
        console.log(this.props.profile);
        const {profile} = this.props.profile;
        const { handleSubmit } = this.props;

        return (
            <div className="row">
                <Col lg={10}>
                    <Tabs defaultActiveKey={1} id="uncontrolled-tab-example">
                        <Tab eventKey={1} title="Vendor Data">
                            <ProfileForm onSubmit={this.handleSubmit}  data = {this.props.profile}/>
                        </Tab>
                        <Tab eventKey={3} title="Events Calendar">
                            <EventsCalendar/>
                        </Tab>
                    </Tabs>

                </Col>

                <Col lg={2}>
                    <Upload/>
                </Col>
            </div>
        );
    }
}

function mapStateToProps(state) {

    return {
        profile: state.default.profile,
    };
}

function mapDispatchToProps(dispatch) {
    return {
        actions: bindActionCreators(profileActions, dispatch)
    };
}

Profile = reduxForm({
    form: 'profileForm' // a unique name for this form
})(Profile);

export default connect(mapStateToProps, mapDispatchToProps)(Profile);

当我打字时,我在控制台中看到状态正在改变

enter image description here

附加的表单组件

import React, {Component} from 'react';
import {Field, reduxForm} from 'redux-form';
import FieldFormControl from '../../common/FieldFormControl';

import {
    FormGroup,
    FormControl,
    ControlLabel,
    Button

} from 'react-bootstrap';

class ProfileForm extends Component {
    render() {
        const {handleSubmit, profile, pristine, reset, submitting} = this.props;

        return (
            <form onSubmit={handleSubmit}>
                <FormGroup controlId="signup-name">
                    <Field type="text" name="firsname" placeholder="test" value component={FieldFormControl}>Vorname</Field>
                </FormGroup>
                <FormGroup controlId="signup-username">
                    <Field type="text" name="lastname" placeholder={profile.username} value={profile.username} component={FieldFormControl}>Name</Field>
                </FormGroup>
                <FormGroup controlId="signup-email">
                    <Field type="text" name="email" placeholder={profile.username} value={profile.username} component={FieldFormControl}>Vorname</Field>
                </FormGroup>

                <Button
                    bsStyle="primary"
                    type="submit"
                    //disabled={pristine || submitting}
                    block
                >Speichern</Button>
            </form>
        );
    }
}

// Decorate the form component
ProfileForm = reduxForm({
    form: 'profileForm' // a unique name for this form
})(ProfileForm);

export default ProfileForm;

Bootstrap 覆盖与 redux-form 兼容

import React, { Component } from 'react';
import {FormGroup, FormControl, ControlLabel} from 'react-bootstrap';

export default class FieldFormControl extends Component {

    render () {

        const { placeholder, type, input, meta} = this.props;

        return (
            <FormGroup controlId={input.name} validationState={meta.error ? 'error' : 'success'}>
                <ControlLabel>{this.props.children}</ControlLabel>
                <FormControl type={type} placeholder={placeholder} value={input.value} onChange={input.onChange} />
                <FormControl.Feedback />
            </FormGroup>
        );
    }
}

最佳答案

Field 组件中删除 value 属性,redux-form 负责更新值并将其传递给您传递的 component 。我假设这里的想法是提供初始值,但这不是这样做的地方。

<Field type="text" name="email" placeholder={profile.username} component={FieldFormControl}>Vorname</Field>

您还可以将所有 input 属性传递给 FieldFormControl 中的 FormControl,以便获得 onFocusonBlur等,都是由redux-form提供的。

<FormControl placeholder={placeholder} {...input} />

如果您想用值初始化字段,请使用 initialValues当您使用 reduxForminitialize 连接时如果需要在表单安装后发生。

最后,您使用 combineReducers 两次,导致大多数 reducer 以您不希望的方式嵌套。为了简化这一点,我将在您的 reducers/index.js 文件中导入 routerReducer,并将其添加到您的 combineReducers 中。

const rootReducer = combineReducers({
    // short hand property names
    session,
    profile,
    map,
    form: formReducer,
    routing: routerReducer,
});

然后,在您的商店中,您将拥有

const store = createStore(
    reducers,
    applyMiddleware(...middleware),
);

然后您应该会看到您的状态中包含所有 key ( session 、配置文件、表单、路由等),而不仅仅是默认 key 和路由。

关于reactjs - redux-form 无法在字段中输入值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42468027/

相关文章:

javascript - 处理 Redux 和 React 错误的最佳实践

reactjs - 如何从 useEffect 访问当前的 redux 状态?

javascript - 从react-admin中的自定义函数回调修改特定的redux-form值

material-ui - DatePicker(material-ui-picker) onChange 无法传值给redux-form onChange事件

javascript - 针对不同提交类型的 Redux 表单验证

android - 如何在 React Native 中实现类似 snapchat 的圆形动画倒计时组件?

reactjs - 使用 react-dnd 和 useDrag 和 useDrop 进行测试

javascript - react 调整大小更改组件

javascript - 如何使用 jest 在一定时间的模拟时间后运行断言测试?

reactjs - 仅在 React js 中首次加载页面时更新状态变量