2017-10-05 19 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> 
    ) 

編集をクリックしたときにモーダルフォーム要素をあらかじめ入力します。私は

let {dish, ingredients} = this.props 

の代わりthis.stateを提供する場合、入力とテキストエリアフィールドを移入することができています。しかし、フォームフィールドは編集不可能になります。だからformsを参照して、私はモーダルコンポーネントの状態を変更しようとしています。私のコードでcomponentWillReceivePropsは解雇されることはありませんか?この状況でコンポーネントWillRecievePropsはどのように正しく機能しますか?新しい小道具でモーダルコンポーネントを更新するには? editItem状態が設定されている場合、あなたはModelコンポーネントをアンマウントし、content小道具でそれを再マウントされているので、あなたの場合は

答えて

2

あなたはcomponentDidMountを使用する必要があります。その場合、componentWillRecceivePropsは発砲されませんが、componentDidMountが発砲します。だからあなたのcomponentWillReceivePropsロジックは

componentDidMount(){ 
    console.log(this.props) // Never fired..why??  
    let {dish, ingredients} = this.props.content 
    this.setState({ 
    dish:dish, ingredients:ingredients 
    }) 
} 
よう componentDidMountに移動します
関連する問題