Redux-Form初始值

时间:2017-05-23 22:55:02

标签: reactjs redux react-redux redux-form

所以我尝试加载一个预先填充了我商店值的Redux表单。但是,除了null之外,我无法获得任何回报。现在已经在这几个小时了,并且已经阅读了几个尝试不同事物的SO示例,并认为我只是在墙上。

遵循此Redux Form Initializing from State example

  • Redux:3.6.0
  • React-Redux:5.0.3
  • Redux-Form:6.6.3
  • 反应:15.4.2

有一个父组件正在呈现作为表单的子组件。为了简洁起见,将最少的代码放在一起并尽可能使名称通用。一切都很好,但我认为问题依赖于没有正确连接到我的商店。或者我应该只是在componentWillMount

上加载数据

父组件:

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { fetchUser } from '../actions/usersActions';

import ChildForm from './ChildForm.jsx'

@connect((store) => {
  return{
    user: store.users.user
  }
})

export default class Parent extends Component{
  componentWillMount(){
    this.props.dispatch(fetchUser(this.props.match.params.id))
  }
  submit = (values) => {//do some stuff}

  render(){
    return(
      <ChildForm onSubmit={this.submit} />
    );
  }
}

ChildForm:

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Field, reduxForm } from 'redux-form';
import { user } from './reducers/usersReducer.js';

class ChildForm extends Component{
  render(){
    console.log('FORM STATE >>>>>>>>>>', this.state); //Returns NULL
    const { handleSubmit } = this.props;
    return(
      <form onSubmit={handleSubmit}>
        <div>
          <label htmlFor="firstName">First Name</label>
          <Field name="first_name" component="input" type="text"/>
        </div>
        <button type="submit">Submit</button>
      </form>
    );
  }    
}

ChildForm = reduxForm({
  form: 'childForm',
  enableReinitialize : true // I found this in another SO Example
})(ChildForm);

ChildForm = connect(
  state => ({
    user: state.user,
    initialValues: state.user
  }),
  { fetchUser }
)(ChildForm)

export default ChildForm;

enableReinitialize SO

usersReducer.js

export default function reducer(state={
  user: {},
}, action){
  switch (action.type){
    case "FETCH_USER_FULFILLED":{
      return{
        ...state,
        user: action.payload
      }
    }
  }
  return state;
}

所以这就是我现在所处的位置。可以获取页面,表单和提交所有工作。但是,我似乎无法弄清楚如何将我的Store值输出到表单字段中。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

看起来所有内容都已正确连线,但我没有在商店中提取正确的对象。

ChildForm = connect(
  state => ({
    initialValues: state.users.user
  }),
  { fetchUser }
)(ChildForm)

......总是很少