Redux Form,如何从组件状态设置InitialValue?

时间:2017-08-07 04:26:14

标签: reactjs redux redux-form

在我的组件中,我有以下内容:

componentWillReceiveProps(nextProps) {
  if (nextProps.industries.items.length > 0) {
    this.setState({
      industry_item_id : nextProps.industries.items.find(el => el.title === "XXXX").id
    });
  }

然后我想在我的Redux Form的initialValue中使用这个值,如下所示:

myForm = reduxForm({
  form: 'myForm',
  initialValues: {
    industry_id: this.state.industry_item_id
  },  
})(myForm);

...
export default connect(mapStateToProps, mapDispatchToProps)(myForm);

如何在initialValues中使用this.state?此外,未在ComponentMount上定义this.state.industry_item_id,当this.state.industry_item_id的值设置为componentWillReceiveProps(nextProps)时,这是否有效?

我正在使用"redux-form": "^6.6.3"

4 个答案:

答案 0 :(得分:2)

您可以使用初始化操作随时设置表单的初始值(即,当您定义要设置的所有值时)。

import { initialize } from 'redux-form';

然后在组件的某处使用:

this.props.dispatch(initialize(<name of your form>, <values you want to set>));

答案 1 :(得分:2)

在容器中的mapStateToProps函数中添加:

const mapStateToProps = (state, ownProps) => (
    initialValues: fromJS({
           industry_id: ownProps.industry_item_id
        })
)

答案 2 :(得分:0)

这是对上述问题的一个很好的参考: http://redux-form.com/6.0.0-alpha.4/examples/initializeFromState/

componentWillReceiveProps(nextProps) {
    if (nextProps.industries.items.length > 0) {
       this.setState({
         industry_item_id : nextProps.industries.items.find(el => el.title === "XXXX").id
       }, () => {
        // callback of setState, because setState is async.
        // dispatch the action via this function.
        this.props.load(this.state.industry_item_id);
       });
    }
 }


 myForm = reduxForm({
     form: 'myForm',
     initialValues: {
         // Connect the value through industry reducer.
         industry_id: state.industryReducer.id
     },  
 })(myForm);

 ...
 export default connect(mapStateToProps, mapDispatchToProps)(myForm);

行动和减少者:

const LOAD = 'redux-form-examples/account/LOAD'

const reducer = (state = {}, action) => {
  switch (action.type) {
    case LOAD:
      return {
        data: action.data
      }
    default:
      return state
  }
}

/**
 * Simulates data loaded into this reducer from somewhere
 */
export const load = data => ({ type: LOAD, data })

export default reducer

答案 3 :(得分:0)

在我的reduxForm组件中使用此方法对我有用:

componentWillMount () { this.props.initialize({ name: 'value' }) }

其中“名称”对应于表单字段的名称。 希望对您有所帮助。