useEffect 如何比较以前和更新的道具

Ven*_*son 5 reactjs

我正在将基于类的Heading组件转换为功能组件,但该组件使用 3 个生命周期钩子componentDidMountcomponentWillUnmountcomponentDidUpdate

我更换了componentDidMountcomponentWillUnmount但是如何更换componentDidUpdate?它正在将更新prop值与旧prop值进行比较。

代码沙箱链接。

应用程序组件:

import React, { Component } from "react";
import { Heading } from "./components/Heading";
import { HeadingHook } from "./components/HeadingHook";

export class App extends Component {
  state = {
    flag: false,
    mountUnmount: true
  };

  toggleChangeFlag = () => {
    if (this.state.mountUnmount) {
      this.setState({
        flag: !this.state.flag
      });
    }
  };

  toggleMountUnmount = () => {
    this.setState({
      flag: false,
      mountUnmount: !this.state.mountUnmount
    });
  };

  render() {
    return (
      <>
        <div>
          <p>Controls :</p>
          <button onClick={this.toggleChangeFlag}>Change Flag</button>
          <button onClick={this.toggleMountUnmount}>Mount & Unmount</button>
        </div>
        {this.state.mountUnmount && <Heading flag={this.state.flag} />}
        {/* Comment above line to use useEffect Heading Component */}
        {/* {this.state.mountUnmount && <HeadingHook flag={this.state.flag} />} */}
      </>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

基于类的标题组件:

import React, {Component} from 'react';

export class Heading extends Component {

    handleProps() {
        if (this.props.flag) {
            alert(this.props.flag);
        } else {
             alert(this.props.flag);
        }
    };

    componentDidMount() {
        this.handleProps();
    }

    componentWillUnmount() {
        this.handleProps();
    }

    componentDidUpdate(prevProps) {
        if (this.props.flag !== prevProps.flag) {
            this.handleProps();
        }
    }

    render() {
        return <h1>Hello World!</h1>;
    }

}
Run Code Online (Sandbox Code Playgroud)

useEffect 标题组件:

import React, { useEffect } from "react";

export const HeadingHook = (props) => {
  const handleProps = () => {
    if (props.flag) {
      alert(props.flag);
    } else {
      alert(props.flag);
    }
  };

  useEffect(() => {
    handleProps();
    return () => {
      handleProps();
    };
  });

  return <h1>Hello World!</h1>;
};
Run Code Online (Sandbox Code Playgroud)

Shu*_*tri 3

您需要做的就是将依赖项数组传递给 useEffect 以确保效果何时运行。在您当前的实现中, useEffect 不仅在初始渲染时调用,而且在每次渲染时调用。要仅在初始渲染时调用它,您需要传递一个空数组作为第二个参数。但是,如果您还希望效果在参数更改时运行,则可以在依赖项数组中传入该参数。

其次,函数式组件没有this关键字,它们接收的 props 是通过函数的参数来获取的。

const Heading = ({flag}) => {


    useEffect(() => {
        const handleProps = () => {
          if (flag) {
            alert(flag);
          } else {
            alert(flag);
          }
         };
        handleProps();
        return () => {
            handleProps();
        }

    }, [flag]);
    return <h1>Hello World!</h1>;
};
Run Code Online (Sandbox Code Playgroud)