Redux表单 - initialValues不用状态更新

时间:2016-08-10 18:49:53

标签: reactjs redux react-redux redux-form

我在使用redux-form设置初始表单字段值时遇到了一些问题。

我正在使用redux-form v6.0.0-rc.3并对v15.3.0做出反应。

所以这是我的问题,我有一个用户网格,当点击用户行时,我正在导航到编辑用户页面并在网址中包含用户ID。然后在编辑用户页面上,我抓住id并调用fetchUser(this.props.params.id),这是一个返回this.state.users的动作创建者。然后我尝试通过调用:

来设置表单初始值
function mapStateToProps(state) {
    return { initialValues:  state.users.user }
}

根据我的理解,这应该将initialValues设置为state.users.user,并且每当更新此状态时,也应该更新initialValues。对我来说情况并非如此。 InitialValues被设置为先前单击的用户行(即this.state.users.user的先前状态)。所以我决定测试这个并为这个组件添加一个按钮,当它被点击时,我再次使用硬编码的用户ID调用fetchUser:

this.props.fetchUser('75e585aa-480b-496a-b852-82a541aa0ca3');

这是正确更新状态,但initialValues的值不会更改。更新状态时不会更新。我在旧版本的redux-form上测试了这个完全相同的过程,它按预期工作。

我在这里做错了什么,或者这是我正在使用的版本的问题。

用户编辑表单 -

class UsersShowForm extends Component {

    componentWillMount() {
        this.props.fetchUser(this.props.params.id);
    }

    onSubmit(props){
        console.log('submitting');
    }

    changeUser() {
        this.props.fetchUser('75e585aa-480b-496a-b852-82a541aa0ca3');
    }

    renderTextField(field) {
        return (
      <TextField 
        floatingLabelText={field.input.label}
        errorText={field.touched && field.error}
        fullWidth={true}
        {...field.input}
      />)
    }

    render() {
        const { handleSubmit, submitting, pristine } = this.props;

        return(

            <div>
                <form onSubmit={handleSubmit(this.onSubmit.bind(this))} className="mdl-cell mdl-cell--12-col">

                    <Field name="emailAddress" component={this.renderTextField} label="Email Address"/>

                    <Field name="firstName" component={this.renderTextField} label="First Name"/>

                    <Field name="lastName" component={this.renderTextField} label="Last Name"/>
                </form>

                <RaisedButton onClick={this.changeUser.bind(this)} label="Primary" primary={true} />
            </div>

        );
    }
}

function mapStateToProps(state) {
    return { initialValues:  state.users.user }
}

UsersShowForm = reduxForm({
  form: 'UsersShowForm'
})(UsersShowForm)

UsersShowForm = connect(
  mapStateToProps,
  actions              
)(UsersShowForm)

export default UsersShowForm

用户减速机 -

import {
    FETCH_USERS,
    FETCH_USER
} from '../actions/types';

const INITIAL_STATE = { all: [], user: {} };

export default function(state = { INITIAL_STATE }, action) {
    switch (action.type) {
        case FETCH_USERS:
            return {...state, all: action.payload };
        case FETCH_USER:
            return {...state, user: action.payload };
        default:
            return state;
    }

}

减速指数 -

import { combineReducers } from 'redux';
import { reducer as formReducer } from 'redux-form';
import usersReducer from './users_reducer';

const rootReducer = combineReducers({
    form: formReducer,
    users: usersReducer
});

export default rootReducer;

3 个答案:

答案 0 :(得分:39)

更新到redux-form v6.0.0-rc.4后,我遇到了同样的问题。

我解决了将enableReinitialize设置为true

的问题
UsersShowForm = reduxForm({
  form: 'UsersShowForm',
  enableReinitialize: true
})(UsersShowForm)

答案 1 :(得分:7)

要使用资源中的数据预填充redux-form表单,您可以使用initialValues道具,在使用reduxForm连接器装饰组件/容器时自动读取。 initialValues中的键与表单字段中的name匹配非常重要。

注意:首先应用reduxForm()装饰器,然后应用redux中的connect()。反之亦然。

使用redux-form 7.2.3:

const connectedReduxForm = reduxForm({
 form: 'someUniqueFormId',
  // resets the values every time the state changes
  // use only if you need to re-populate when the state changes
  //enableReinitialize : true 
})(UserForm);

export default connect(
  (state) => { 
    // map state to props
    // important: initialValues prop will be read by redux-form
    // the keys must match the `name` property of the each form field
    initialValues: state.user 
  },
  { fetchUser } // map dispatch to props
)(connectedReduxForm) 

来自官方文件:

  

提供给initialValues prop或reduxForm()配置参数的值将被加载到表单状态,然后作为&#34; pristine&#34;处理。它们也将是调度reset()时返回的值。除了保存&#34;原始&#34;值,初始化表单将覆盖任何现有值。

official documentation

中查找更多信息和完整示例

答案 2 :(得分:0)

在我的情况下,我有Redux表单,2路由,其网址参数更改很小。 在组件之间切换时,道具没有更新。 它一直显示空白表格。

示例:baseurl/:id/personal -> baseurl/:id/employment

调试之后,我发现mapStateToProps在设置初始值的某个时间没有触发。

<React.Fragment>
  <Route
    exact={true}
    path="/path1"
    component={PersonalDetails}
    key="personal"
  />
  <Route
    exact={true}
    path="/path1/employment"
    component={Employment}
    key="employment"
  />
</React.Fragment>

destroyOnUnmount 设置为 false mapStateToProps修复了我的问题,该问题的默认值为true。

    enableReinitialize: true,
    destroyOnUnmount: false

上面使用示例:

UsersShowForm = reduxForm({
  form: 'UsersShowForm',
  enableReinitialize: true,
  destroyOnUnmount: false
})(UsersShowForm)

了解更多:destroyOnMount