2017-10-05 51 views
0

我有一个用于将配方保存到列表的模块组件。如何使用新道具更新模态组件

modal = <Modal saveRecipe={this.saveRecipe} closeModal={this.toggleModal}/> 

此外,我想用这个相同的模式组件编辑配方,所以我这样做

if(this.state.editItem){ 
    modal = <Modal content={editContent} saveRecipe={this.saveRecipe} closeModal={this.toggleModal}/> 
    } 
else{ 
    modal = <Modal saveRecipe={this.saveRecipe} closeModal={this.toggleModal}/> 
} 

所以我能够向下传递的对象来进行编辑,以模态分量。 模态组件有一个文本输入和一个textarea元素。

constructor(props) { 
    super(props); 
    this.state = {dish: '', ingredients:[]};  
} 
componentWillReceiveProps(nextProps){ 
    console.log(nextProps) // Never fired..why??  
    let {dish, ingredients} = nextProps.content 
    this.setState({ 
    dish:dish, ingredients:ingredients 
    }) 
} 
render(){ 
    let {dish, ingredients} = this.state 
    console.log(this.props) // {dish:"new dish", ingredients:['ingreds']} 
    return(
    <div className="modal"> 
    <input type="text" ref="title" value={dish} /> 
    <textarea ref="ingredients" value={ingredients}></textarea> 
    </div> 
    ) 

我想单击编辑时预先填充模态表单元素。我能够填充输入和textarea的领域,如果我提供

let {dish, ingredients} = this.props 

,而不是this.state。但是,表单域变得不可编辑。所以参考forms,我试图改变模态组件的状态。在我的代码componentWillReceiveProps永远不会被解雇? componentWillRecieveProps在这种情况下如何工作?如何用新道具更新模态组件?

回答

2

你的情况,你必须使用componentDidMount因为当editItem状态时,那么你就卸载Model组件,并与content道具重新安装它。所以在这种情况下,componentWillRecceiveProps不会被解雇,但componentDidMount将被解雇。因此,将componentWillReceiveProps逻辑移动到componentDidMount就像

componentDidMount(){ 
    console.log(this.props) // Never fired..why??  
    let {dish, ingredients} = this.props.content 
    this.setState({ 
    dish:dish, ingredients:ingredients 
    }) 
}