首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用类组件生命周期中的依赖关系来响应功能组件useEffect挂钩

用类组件生命周期中的依赖关系来响应功能组件useEffect挂钩
EN

Stack Overflow用户
提问于 2021-09-19 11:27:10
回答 2查看 2K关注 0票数 3

我在函数组件中使用带有依赖项的useEffect钩子,这样依赖项就会发生变化,useEffect函数将像这样重新运行:

代码语言:javascript
复制
const [show, setShow] = React.useState(false);

React.useEffect(() => {
 
    console.log("Do something")

} , [show]);

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-09-19 11:39:50

您可以使用componentDidMountcomponentDidUpdate的组合

代码语言:javascript
复制
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");
  }
}
票数 6
EN

Stack Overflow用户

发布于 2021-09-19 11:52:15

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

代码语言:javascript
复制
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>;
           }
       }

如果ypu从该方法返回true,则说明组件应该更新,false以其他方式表示,组件不会更新。

您还可以从PureComponent (PureComponent)扩展,它将自动跟随道具和状态:

代码语言:javascript
复制
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不会重新添加组件。

还有其他方法,如componentDidUpdate (链接)和componentDidMount (链接)。首先,当组件重登时调用:

代码语言:javascript
复制
componentDidUpdate(prevState) {
  if (this.state.userID !== prevState.userID) {
    this.fetchData(this.state.userID);
  }
}

谈到第二个问题,它将在DOM中设置组件时调用。

在您的例子中使用componentDidUpdate

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69242802

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档