React功能组件useEffect钩子,在类组件生命周期中依赖相等



我在有依赖的功能组件中使用了useEffect钩子,这样当依赖改变时,useEffect函数会像这样重新运行:

const [show, setShow] = React.useState(false);
React.useEffect(() => {

console.log("Do something")
} , [show]);

我想知道什么是可用的在react的类组件做这样的?是否有任何生命周期方法具有此功能?

您可以使用componentDidMountcomponentDidUpdate的组合:

componentDidMount(){ //use this method if you want to trigger the side effect first time
console.log("Do something")
}
componentDidUpdate(prevProps,prevState) {
if (this.state.show !== prevState.show) {
console.log("Do something");
}
}

控制您的组件使用shouldComponentUpdate(文章的链接)。它有两个参数nextPropsnextState. 您可以比较this.state.fieldnextState.field,如果它们不同,则产生副作用:

class ClickButton extends React.Component {

constructor(props) {
super(props);
this.state = {class: "off", label: "press"};
this.press = this.press.bind(this);
}

shouldComponentUpdate(nextProps, nextState){
if(nextState.class !== this.state.class){
return true
}
return false;
}

press(){
var className = (this.state.class==="off")?"on":"off";
this.setState({class: className});
}
render() {
return <button onClick={this.press} className={this.state.class}>{this.state.label}</button>;
}
}

返回true从这个方法中,它告诉React组件应该更新,false否则,组件将不会更新。

也可以从PureComponent(PureComponent)扩展,它会自动跟随props和state:

class ClickButton extends React.PureComponent {

constructor(props) {
super(props);
this.state = {class: "off", label: "press"};

this.press = this.press.bind(this);
}

press(){
var className = (this.state.class==="off")?"on":"off";
this.setState({class: className});
}

render() {
return <button onClick={this.press} className={this.state.class}>{this.state.label}</button>;
}
}

但是它做了一个肤浅的比较(通过引用)。如果你的状态中有嵌套字段,并且它们在变化,PureComponent就不会渲染Component。

还有其他方法,如componentDidUpdate(link)和componentDidMount(link)。首先,在组件渲染时调用:

componentDidUpdate(prevState) {
if (this.state.userID !== prevState.userID) {
this.fetchData(this.state.userID);
}
}

说到第二个,当组件在DOM中设置时,它将被调用。

使用componentDidUpdate

相关内容