2017-08-07 59 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 
     }) 
) 
相關問題