2017-08-07 64 views
0

在我的部分,我有以下几点:Redux Form,如何从组件状态设置InitialValue?

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

那么我想在我的终极版形式的初值使用这个值,像这样:

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

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

我如何使用this.state的initialValues内?另外,this.state.industry_item_id没有在ComponentMount上定义,当this.state.industry_item_id的值设置为componentWillReceiveProps(nextProps)时,它是否会工作?由于

通知你,我用“终极版形式”:“^ 6.6.3”,

回答

1

您可以使用初始化动作来设置形式随时随地您的初始值(即当所有的值要设置被定义)。

import { initialize } from 'redux-form'; 

然后在您的组件使用的地方:

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

工作得很好。谢谢 – AnApprentice

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 
1

在您的容器中的mapStateToProps函数中加入:

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