簡體   English   中英

在React類組件中進行分解

[英]Destructuring in a React Class Component

是否有另一種方法可以在React Class組件中使用ES6解構,而不必在每種方法中都這樣做?

我在constructorcomponentDidMount()componentDidUpdate()render()方法中使用了相同的道具( this.prop.page ):

class SinglePage extends React.Component {

  constructor(props) {
    super(props);
    const { page } = this.props;
    //...
  }

  componentDidMount() {
    const { page } = this.props;
    //...
  }

  componentDidUpdate() {
    const { page } = this.props;
    //...
  }

  render() {
    const { page } = this.props;
    return (
     //...
    );
  }
}

exports default SinglePage;

有沒有辦法做到一次?

是否可以使用帶有鈎子的最新react版本。 UseEffect將替換didMount和didUpdate,並且也不會使用功能組件來構造函數。 我建議閱讀有關useEffect掛鈎的本文。 https://overreacted.io/a-complete-guide-to-useeffect/

useEffect可以處理在類組件中使用生命周期方法的情況。 您可以根據需要使用一個或多個。

import React, { useEffect } from React;

function SinglePage({ page }) {

  useEffect(() => {
    // componentDidMount() {
  }, []); // empty array here means it'll only run after the first render

  useEffect(() => {
    // componentDidMount() {
    // componentDidUpdate() {
  }); // no second are means it runs after every render

  useEffect(() => {
    // componentDidMount() {
    // componentDidUpdate() {
  }, [page]); // runs on initial render and whenever `page` changes

  useEffect(() => {
    return () => cancelTheThings(); // componentWillUnMount() {
  }); // return a function from your useEffect function to have it run before unmount

  return {
    //...
  }
}

export default SinglePage;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM