関数コンポーネント内のReactJSライフサイクルメソッド 質問する

関数コンポーネント内のReactJSライフサイクルメソッド 質問する

クラス内にコンポーネントを記述する代わりに、関数構文を使用したいと思います。

関数コンポーネント内でcomponentDidMountをオーバーライドするにはどうすればよいですか?それは可能ですか?componentWillMount

const grid = (props) => {
    console.log(props);
    let {skuRules} = props;

    const componentDidMount = () => {
        if(!props.fetched) {
            props.fetchRules();
        }
        console.log('mount it!');
    };
    return(
        <Content title="Promotions" breadcrumbs={breadcrumbs} fetched={skuRules.fetched}>
            <Box title="Sku Promotion">
                <ActionButtons buttons={actionButtons} />
                <SkuRuleGrid 
                    data={skuRules.payload}
                    fetch={props.fetchSkuRules}
                />
            </Box>      
        </Content>  
    )
}

ベストアンサー1

編集:の導入によりHooks機能コンポーネントでは、ライフサイクルのような動作と状態を実装することが可能です。現在

フックは、クラスを書かずに状態やその他のReactの機能を利用できる新しい機能提案です。Reactの一部としてリリースされました。バージョン16.8.0

useEffectフックはライフサイクル動作を複製するために使用でき、useState関数コンポーネントに状態を保存するために使用できます。

基本的な構文:

useEffect(callbackFunction, [dependentProps]) => cleanupFunction

次のようなフックでユースケースを実装できます。

const grid = (props) => {
    console.log(props);
    let {skuRules} = props;

    useEffect(() => {
        if(!props.fetched) {
            props.fetchRules();
        }
        console.log('mount it!');
    }, []); // passing an empty array as second argument triggers the callback in useEffect only after the initial render thus replicating `componentDidMount` lifecycle behaviour

    return(
        <Content title="Promotions" breadcrumbs={breadcrumbs} fetched={skuRules.fetched}>
            <Box title="Sku Promotion">
                <ActionButtons buttons={actionButtons} />
                <SkuRuleGrid 
                    data={skuRules.payload}
                    fetch={props.fetchSkuRules}
                />
            </Box>      
        </Content>  
    )
}

useEffectコンポーネントがアンマウントされたときに実行される関数を返すこともできます。これを使用してリスナーの登録を解除し、次の動作を再現できますcomponentWillUnmount

例:componentWillUnmount

useEffect(() => {
    window.addEventListener('unhandledRejection', handler);
    return () => {
       window.removeEventListener('unhandledRejection', handler);
    }
}, [])

特定のイベントを条件にするにはuseEffect、変更をチェックするための値の配列を指定します。

例:componentDidUpdate

componentDidUpdate(prevProps, prevState) {
     const { counter } = this.props;
     if (this.props.counter !== prevState.counter) {
      // some action here
     }
}

同等のフック

useEffect(() => {
     // action here
}, [props.counter]); // checks for changes in the values in this array

この配列を含める場合は、時間の経過とともに変化するコンポーネント スコープのすべての値 (props、state) を含めるようにしてください。そうしないと、以前のレンダリングの値を参照することになります。

使用には微妙な点がいくつかありますuseEffect。APIを確認してください。Here


v16.7.0以前

関数コンポーネントの特性として、Reacts ライフサイクル関数やキーワードにアクセスできないという点があります。ライフサイクル関数を使用する場合は、クラスthisを拡張する必要があります。React.Component

class Grid extends React.Component  {
    constructor(props) {
       super(props)
    }

    componentDidMount () {
        if(!this.props.fetched) {
            this.props.fetchRules();
        }
        console.log('mount it!');
    }
    render() {
    return(
        <Content title="Promotions" breadcrumbs={breadcrumbs} fetched={skuRules.fetched}>
            <Box title="Sku Promotion">
                <ActionButtons buttons={actionButtons} />
                <SkuRuleGrid 
                    data={skuRules.payload}
                    fetch={props.fetchSkuRules}
                />
            </Box>      
        </Content>  
    )
  }
}

関数コンポーネントは、追加のロジックを必要とせずにコンポーネントをレンダリングしたい場合に便利です。

おすすめ記事