简体   繁体   English

在React类组件中进行分解

[英]Destructuring in a React Class Component

Is there another way of using ES6 destructuring in a React Class component without having to do it in each method? 是否有另一种方法可以在React Class组件中使用ES6解构,而不必在每种方法中都这样做?

I am using the same prop ( this.prop.page ) in the constructor , componentDidMount() , componentDidUpdate() and render() methods: 我在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;

Is there a way of do it just once? 有没有办法做到一次?

There is if you can use latest react version with hooks. 是否可以使用带有钩子的最新react版本。 UseEffect will replace didMount and didUpdate and also no constructor with functional component. UseEffect将替换didMount和didUpdate,并且也不会使用功能组件来构造函数。 I recommend to read this article about useEffect hook. 我建议阅读有关useEffect挂钩的本文。 https://overreacted.io/a-complete-guide-to-useeffect/ https://overreacted.io/a-complete-guide-to-useeffect/

useEffect is there to handle the cases you would use lifecycle methods for in class components. useEffect可以处理在类组件中使用生命周期方法的情况。 You can use one or more, depending on your needs. 您可以根据需要使用一个或多个。

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