【发布时间】:2019-10-11 19:25:51
【问题描述】:
我正在将基于类的 Heading 组件转换为功能组件,但该组件正在使用 3 个生命周期挂钩 componentDidMount、componentWillUnmount 和 componentDidUpdate。
我替换了componentDidMount 和componentWillUnmount,但是如何替换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} />} */}
</>
);
}
}
基于类的标题组件:
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>;
}
}
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>;
};
【问题讨论】:
标签: reactjs