如何在 ReactJs 中正确使用 shouldComponentUpdate() 和 componentWillUpdate() 方法? [英] How to use shouldComponentUpdate() and componentWIllUpdate() method correctly in ReactJs?

查看:74
本文介绍了如何在 ReactJs 中正确使用 shouldComponentUpdate() 和 componentWillUpdate() 方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我使用 componentWillReceiveProps 从 redux 获取数据后更新我的组件本地对象之前.

Before i was using componentWillReceiveProps to update my component local object after getting data from redux.

componentWillReceiveProps(nextProps) {
    if (nextProps.editUser && !nextProps.loading && !isEqual(this.state.user, nextProps.editUser)){
        this.setState({user:{
          name:nextProps.editUser.name,
          email:nextProps.editUser.email,
        }}, function(){
          this.setState({addModalUserEdit:true});
        });
    }
}

但现在我想按照反应生命周期在反应文档中使用 shouldComponentUpdate 和 componentWillUpdate .

But now i want to use shouldComponentUpdate and componentWillUpdate as in react documentation as per react life cycle.

shouldComponentUpdate(nextProps, nextState){
    if (nextProps.editUser && !nextProps.loading && !isEqual(this.state.user, nextProps.editUser)){
      return true;
    }
    return false;
}

componentWillUpdate(nextProps, nextState) {
    if (nextProps.editUser && !nextProps.loading && !isEqual(this.state.user, nextProps.editUser)){
        this.setState({user:{
          name:nextProps.editUser.name,
          email:nextProps.editUser.email,
        }}, function(){
          this.setState({addModalUserEdit:true});
        });
    }
}

但我产生了一个错误

超出最大更新深度.当组件在 componentWillUpdate 内重复调用 setState 或组件DidUpdate.React 将嵌套更新的数量限制为防止无限循环."

"Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops."

请指导我在理解 React 生命周期方面做错了什么.

Please guide me what i am doing wrong in understanding react life cycle.

提前致谢.

推荐答案

shouldComponentUpdate 用于决定 props 或 state 的变化是否影响到组件输出.

shouldComponentUpdate use to decide that changes in props or the state have affected to component output or not.

componentDidUpdate 将在组件输出有更新时触发.

componentDidUpdate will be triggered when there is an update on component output.

shoudComponentUpdate 有两个参数,nextPropsnextState.其中包含道具和状态的新更新.并返回一个布尔值.

shoudComponentUpdate take 2 arguments, nextProps and nextState. that contains a new update of props and state. and returning a boolean.

这篇关于如何在 ReactJs 中正确使用 shouldComponentUpdate() 和 componentWillUpdate() 方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆