草庐IT

react生命周期

K-L‘s Blog 2023-03-28 原文

总结-旧生命周期

初始化阶段: 由ReactDOM.render()触发---初次渲染

  1. constructor()
  2. componentWillMount()
  3. render()
  4. componentDidMount() ===> 常用
    一般在这个钩子中做一些初始化的事,例如:开启定时器,发送网络请求,订阅消息

更新阶段: 由组件内部this.setState()或父组件render触发

  1. shouldComponentUpdate()
  2. componentWillUpdate()
  3. render() ===> 常用
  4. componentDidUpdate()

卸载组件: ReactDOM.unmountComponentAtNode()触发

组件挂载流程

  1. componentWillUnmount() ===> 常用
    一般在这个钩子中做一些收尾的事,例如:关闭定时器,取消订阅消息
    class Count extends React.Component {
            // 最先调用
            constructor(props) {
                super(props);
                console.log('count---constructor');
                this.state = { count: 0 }
            }

            // 组件将要挂载
            //WARNING! To be deprecated in React v17. Use componentDidMount instead.
            componentWillMount() {
                console.log('count---componentWillMount');
            }

            // 组件挂载完毕的钩子
            componentDidMount() {
                console.log('count---componentDidMount')
            }

            componentWillUnmount() {
                console.log('count---componentWillUnmount');
            }

            // 控制更新阀门
            shouldComponentUpdate(nextProps, nextState) {
                console.log('count---shouldComponentUpdate');
                return true;
            }
            // 组件将要更新的钩子
            //WARNING! To be deprecated in React v17. Use componentDidUpdate instead.
            componentWillUpdate(nextProps, nextState) {
                console.log('count---componentWillUpdate')
            }
            // 组件更新之后
            componentDidUpdate(prevProps, prevState) {
                console.log('count---componentDidUpdate');
            }

            add = () => {
                let { count } = this.state;
                count += 1;
                this.setState({ count: count });
            }
            unload = () => {
                root.unmount(document.getElementById('test'));
            }

            // 初始化渲染,状态更新之后 执行
            render() {
                const { count } = this.state;
                console.log('count---render');
                return (
                    <div>
                        <h2>当前求和为: {count}</h2>
                        <button onClick={this.add}>点我加一</button>
                        <button onClick={this.unload}>卸载组件</button>
                    </div>
                )
            }
        }

父组件render流程

      class A extends React.Component {
            constructor(props) {
                super(props);
                this.state = { carName: '奔驰' };
            }
            changeCar = () => {
                this.setState({ carName: '宝马' });
            }
            render() {
                return (
                    <div>
                        <h1>A</h1>
                        <button onClick={this.changeCar}>换车</button>
                        <B carName={this.state.carName} />
                    </div>
                )
            }
        }

        class B extends React.Component {
            // 组件将要接收到新的props的钩子
            //WARNING! To be deprecated in React v17.
            //  Use new lifecycle static getDerivedStateFromProps instead.
            componentWillReceiveProps(props) {
                console.log('count---componentWillReceiveProps', props)
            }
            render() {
                return (
                    <div>
                        <h1>B</h1>
                        <h2>现在的车: {this.props.carName}</h2>
                    </div>
                )
            }
        }

新生命周期

class Count extends React.Component {

            // 最先调用
            constructor(props) {
                super(props);
                console.log('count---constructor');
                this.state = { count: 0 }
            }

            // 使用场景极其罕见,state值取决于props
            static getDerivedStateFromProps(props, state) {
                console.log('getDerivedStateFromProps', props, state);
                return null;
            }

            // 在最近一次渲染之前调用,传值给DidUpdate
            getSnapshotBeforeUpdate = (prevProps, prevState) => {
                console.log('getSnapshotBeforeUpdate');
                return 'nihao';
            }

            // 组件挂载完毕的钩子
            componentDidMount() {
                console.log('count---componentDidMount')
            }

            componentWillUnmount() {
                console.log('count---componentWillUnmount');
            }

            // 控制更新阀门
            shouldComponentUpdate(nextProps, nextState) {
                console.log('count---shouldComponentUpdate');
                return true;
            }
            // 组件更新之后
            componentDidUpdate(prevProps, prevState, snapshotValue) {
                console.log('count---componentDidUpdate', snapshotValue);
            }

            add = () => {
                let { count } = this.state;
                count += 1;
                this.setState({ count: count });
            }
            unload = () => {
                root.unmount(document.getElementById('test'));
            }

            // 初始化渲染,状态更新之后 执行
            render() {
                const { count } = this.state;
                console.log('count---render');
                return (
                    <div>
                        <h2>当前求和为: {count}</h2>
                        <button onClick={this.add}>点我加一</button>
                        <button onClick={this.unload}>卸载组件</button>
                    </div>
                )
            }
        }

有关react生命周期的更多相关文章

  1. ruby-on-rails - Ruby 长时间运行的进程对队列事件使用react - 2

    我有一个将某些事件写入队列的Rails3应用。现在我想在服务器上创建一个服务,每x秒轮询一次队列,并按计划执行其他任务。除了创建ruby​​脚本并通过cron作业运行它之外,还有其他稳定的替代方案吗? 最佳答案 尽管启动基于Rails的持久任务是一种选择,但您可能希望查看更有序的系统,例如delayed_job或Starling管理您的工作量。我建议不要在cron中运行某些东西,因为启动整个Rails堆栈的开销可能很大。每隔几秒运行一次它是不切实际的,因为Rails上的启动时间通常为5-15秒,具体取决于您的硬件。不过,每天这样做几

  2. ruby - 单个 EventMachine react 器中的多个服务器 - 2

    是否可以在单个事件机器中运行多个服务器?我的意思是,多个服务可以由一个客户端连接同时使用。例如,登录服务器对用户进行身份验证,然后用户可以同时使用聊天室和简单的游戏,例如带有单个客户端套接字的跳棋?或者我是否需要为每个服务使用多个事件机器react器? 最佳答案 我试过了,它正在工作:#!/usr/bin/envrubyrequire'eventmachine'moduleEchoServerdefpost_initputs"--someoneconnectedtotheechoserver!"enddefreceive_datad

  3. ruby - 在 Ruby 中查找周期和范围集差异的有效方法 - 2

    我在Ruby中有很多时间范围:period=Time.parse('8:00am')..Time.parse('8:00pm')incidents=[Time.parse('7:00am')..Time.parse('9:00am'),Time.parse('1:00pm')..Time.parse('3:00pm'),Time.parse('1:30pm')..Time.parse('3:30pm'),Time.parse('7:00pm')..Time.parse('9:00pm'),]我正试图在这段时间内获得一系列无事件block。对于以上内容:[Time.parse('9:00

  4. ruby-on-rails - 有没有一种简单的方法可以在 Passenger 的请求周期之外运行垃圾收集? - 2

    unicorn有OobGC可用于在一定数量的请求后运行GC.start的机架中间件。PhusionPassenger中有类似的东西吗? 最佳答案 PhusionPassenger4正式引入了带外垃圾回收机制。它比Unicorn更灵活,允许任意工作,而不仅仅是垃圾收集。http://blog.phusion.nl/2013/01/22/phusion-passenger-4-technology-preview-out-of-band-work/ 关于ruby-on-rails-有没有一种

  5. React通过classnames库添加类 - 2

    React添加Class的方式在vue中添加class是一件非常简单的事情:你可以通过传入一个对象,通过布尔值决定是否添加类:button:class="{active:isFlag,aaa:true}">按钮button>你也可以传入一个数组:h2:class="['aaa','bbb']">HelloVueh2>h2:class="[className1,className2]">HelloVueh2>甚至是对象和数组混合使用:h2:class="['aaa',{active:isFlag}]">HelloVueh2>而在React中就相对繁琐了,React在JSX给了我们开发者足够多的灵

  6. ruby-on-rails - rails 周期性任务 - 2

    我有一个ruby​​onrails应用程序,我试图在其中找到每隔几秒运行一些代码的方法。我发现了很多使用cron或类似cron的实现的信息和想法,但这些只是准确到分钟,并且/或需要外部工具。我想每15秒左右启动一次任务,并且我希望它完全独立于应用程序中(如果应用程序停止,任务也停止,并且没有外部设置)。这用于缓存数据的后台生成。每隔几秒,任务就会收集一些数据,然后将其存储在缓存中,供所有客户端请求使用。该任务非常慢,因此需要在后台运行并且不阻塞客户端请求。我是ruby​​的新手,但有很强的perl背景,我解决这个问题的方法是创建一个间隔计时器和处理程序,它fork、运行代码,然后在完成

  7. 如何使React Router V4路由与React Transition Group(低级API)一起使用 - 2

    从ReactRouterV3过渡到V4后,我再也无法使ReactTransition组低级API工作。React路由器的文档显示了与CSS动画相关的高级API的示例,这些示例与低水平的JS风味不起作用。任何人都设法或知道让这个工作?看答案已经一个月了,所以我想您找到了自己的出路,但可能会对他人有所帮助。我创建了这个:https://www.npmjs.com/package/reeact-router-v4-transition在我遇到同样的问题之后。它在开关组件中提供了一种过渡组。从将开关更改为TransitionSwitch的Appart,它不需要大幅度更改。我将在接下来的几天(可能是星期

  8. ruby-on-rails - Rails 应用程序的生命周期 - 2

    我正在尝试了解Rails应用程序的生命周期。application_controller.rb什么时候运行?是每次更改时只执行一次,还是每次请求时都执行一次?我想了解以下文件:config/environments/*.rb(开发、生产或测试,取决于当前模式)boot.rb环境.rb路线.rb我问这个的原因之一是,我想知道放在哪里比较好初始化代码自定义配置数据编辑:@Gdeglin的回答很好,但我实际上很想知道这些文件中的每一个何时运行。 最佳答案 应用程序Controller.rbApplicationController是所有C

  9. ruby - 在 Sinatra(Ruby) 中,我应该如何创建在应用程序生命周期中只赋值一次的全局变量? - 2

    在Sinatra中,我无法创建在应用程序生命周期中仅分配一次值的全局变量。我错过了什么吗?我的简化代码如下所示:require'rubygems'ifRUBY_VERSION这导致nil2在终端和,2在浏览器中。如果我尝试将@a=1放入initialize方法中,我会在WebApp.run!中遇到错误线。我觉得我错过了一些东西,因为如果我不能有全局变量,那么我如何在应用程序实例化期间加载大数据?beforedo似乎每次有来自客户端的请求时都会被调用。 最佳答案 classWebApp请注意,如果您使用Shotgun或其他在每次请求时

  10. javascript - 使用 React-Router 在路由之间传递 props - 2

    是在React-Router(1.0.0-rc)url参数中的路由之间传递数据的唯一方法吗?我有一个组件A,它使用Historymixin,并且有一个事件处理程序,该事件处理程序发出服务器请求,然后调用that.history.pushState(null,'/B');以过渡到路由B由组件B处理。现在,我想将服务器返回的一些数据作为Prop(例如“登录成功”)传递给组件B,或者以某种方式影响B的状态,但我找不到任何说明这是可能的。有什么办法可以做到这一点,还是我需要将其作为url参数传递? 最佳答案 你有两个选择:将数据作为查询参数

随机推荐