2017-10-31 9 views
0

次のコンポーネントの構造を仮定すると、Parentで自分の状態を更新することはできません。私はそれが働くようにすることができることを知っている子供のステートレスまたは子供の状態を更新するだけですが、私たちのアプリケーションではこれは現在の構造です。これを行うための良い方法はありますか、または再設計する必要はありますか?私たちはアプリケーション内で多くのhttpリクエストを発行することを望んでいないので、親の状態を保ちます。親では、必要なデータを取得し、初期変更を行います。このデータは、次に子コンポーネントを持つ他のコンポーネントに送信され、したがって例の構造になります。この例では印刷されますどのようなリアクション16.0.0親子GrandChild。親の状態を更新してもGrandChildは更新されません

Test: 1235

import * as React from 'react'; 
import * as ReactDOM from 'react-dom'; 

interface IProps { 
} 

interface IState { 
    cases: number[]; 
} 

class Parent extends React.Component<IProps, IState> { 
    constructor(props: IProps) { 
    super(props); 
    this.state = { 
     cases: [1, 2, 3], 
    }; 
    } 

    componentDidMount() { 
    let newCase = 4; 
    let newCases = Array.from(this.state.cases); 
    newCases.push(newCase) 
    this.setState({ 
     cases: newCases 
    }); 
    } 

    render() { 
    return (
     <div> 
     <Child cases={this.state.cases} /> 
     </div> 
    ); 
    } 
} 

interface IChildProps { 
    cases: number[]; 
} 

interface IChildState { 
    cases: number[]; 
} 

class Child extends React.Component<IChildProps, IChildState> { 
    constructor(props: IChildProps) { 
    super(props); 
    this.state = { 
     cases: this.props.cases, 
    }; 
    } 

    componentDidMount() { 
    let newCase = 5; 
    let newCases = Array.from(this.state.cases); 
    newCases.push(newCase) 
    this.setState({ 
     cases: newCases 
    }); 
    } 

    render() { 
    return (
     <GrandChild cases={this.state.cases} /> 
    ); 
    } 
} 

interface IGrandChildProps { 
    cases: number[]; 
} 

interface IGrandChildState { 
} 

class GrandChild extends React.Component<IGrandChildProps, IGrandChildState> { 
    constructor(props: IGrandChildProps) { 
    super(props); 
    } 

    render() { 
    return (
     <div> 
     Test: {this.props.cases.map((value, index) => { 
      return <span key={index}>{value}</span> 
     } 
     )} 
     </div> 
    ); 
    } 
} 

export default Parent 

答えて

3

それはあなたが小道具が変化したときの状態を更新を担当している一つです起きたら、ここでの問題は、あなたが状態に小道具をマッピングしているということです。 componentDidMountだけを使用するので、プロンプトを一度状態にマップするだけです。私は通常、コンポーネントを小道具を自らの状態に変換するのを避けるために、代わりに親が小道具を必要とする方法で小道具を子供に渡し、小道具が子要素で変化するときに状態を変更する心配がないようにします。

他の選択肢は

setCases(cases) { 
    let newCase = 5; 
    let newCases = Array.from(cases); 
    newCases.push(newCase) 
    this.setState({ 
     cases: newCases 
    }); 
    } 

    componentDidMount() { 
    this.setCases(this.props.cases) 
    } 

    componentWillReceiveProps(nextProps) { 
    this.setCases(nextProps.cases); 
    } 

componentDidMountは、初期ロードに状態を設定処理すると、その後componentWillReceivePropsは小道具が変更するたびに状態を変更処理する次componentWillReceivePropsライフサイクルメソッドを使用して行うことです。

+1

一般に、小道具を状態に「同期」させることはほとんどありません。代わりに状態を上げる:https://reactjs.org/docs/lifting-state-up.html –

関連する問題