如何在 ReactJS 中向类添加生命周期方法?

programmingreact jsserver side programming

React 中的每个组件都有一个包含多个阶段的生命周期。程序员通常将此生命周期视为组件的"生命周期"。组件会经历以下事件:挂载、更新、卸载和错误处理。挂载是指添加节点的过程,而更新则需要程序员在 DOM 中更改和修改这些节点。另一方面,卸载会删除节点,错误处理会跟踪您的代码以确保其正常运行且无错误。

这些事件可以与组件的诞生、发展和最终消亡进行比较。您可以在每个 React 生命周期阶段覆盖多个生命周期方法,以在流程中的特定点执行代码。考虑到这一点,让我们来解释一下如何将上述生命周期方法添加到 ReactJS 中的类组件。

关于 React 生命周期方法的详细见解

如您所知,挂载、更新和卸载是主要的 React 生命周期方法。每个阶段使用的方法使对组件执行常见操作变得更加简单。React 开发人员可以直接从 React 组件扩展基于类的组件来访问这些方法。

在 React 16.8 之前,管理生命周期事件的最流行方法需要基于 ES6 类的组件。换句话说,如果我们的代码已经使用功能性 React 组件编写,我们需要将它们重写为使用 React.Component 扩展并包含特定渲染函数的类。

只有这样才能访问三种最流行的生命周期方法,componentDidMount、componentDidUpdate 和 componentWillUnmount。

如何轻松使用本地状态和额外功能?

为了在 React 中使用本地状态以及额外功能,您首先必须将功能补充转换为类组件。

  • 创建一个扩展同名 ES6 类的 React.Component
  • 添加一个空方法 render()。
  • 将函数的主体放在 render() 方法中。
  • 用 this.props 替换 render() 主体中的 props
  • 删除任何剩余的空函数声明。
render() { return ( <div> <h1>Hello, world!</h1> <h2>It is {this.props.date.toLocaleTimeString()}.</h2> </div> ); }

React 组件时钟的定义现在是一个类,而不是一个函数。每次发生更新时,都会调用 render 方法,但只要 <Clock/> 元素在同一个 DOM 节点中呈现,就只会使用该类的一个实例。

向类组件添加生命周期方法

对于包含大量组件的应用程序,释放资源是必不可少的。当时钟首次显示到 DOM 时,我们希望启动一个计时器。React 术语为"挂载"。此外,一旦时钟创建的 DOM 被删除,我们就希望重置该计时器。在 React 中,这被称为"卸载"。

示例

import react from ‘react’; class Clock extends React.Component { constructor(props) { super(props); this.state = {date: new Date()}; } componentDidMount() { } componentWillUnmount() { } render() { return ( <div> <h1>Hello, world!</h1> <h2>It is {this.state.date.toLocaleTimeString()}.</h2> </div> ); } }

输出

Hello, world!
It is 10:27:03 AM.

成功渲染组件的输出会调用一个特定的函数。这是 componentDidMount() 函数。在此处插入一个计时器 −

componentDidMount() { this.timerID = setInterval( () => this.tick(), 1000 ); }

还可以手动向 Class 组件插入更多字段。程序员通常在需要保留不属于数据流的内容时这样做。尽管 ReactJS 自行设置了 this.state 和 this.props,但仍然如此。这些还具有独特的含义,例如计时器 ID。在生命周期函数 componentWillUnmount() 中,我们将停用计时器 -

componentWillUnmount() { clearInterval(this.timerID); }

Clock 组件将每秒执行一次 tick() 方法,我们将最后实现该方法。它将使用该方法。要对组件的本地状态进行编程更新,请使用 setState() −

示例

class Clock extends React.Component { constructor(props) { super(props); this.state = {date: new Date()}; } componentDidMount() { this.timerID = setInterval( () => this.tick(), 1000 ); } componentWillUnmount() { clearInterval(this.timerID); } tick() { this.setState({ date: new Date() } ); } render() { return ( <div> <h1>Hello, world!</h1> <h2>It is {this.state.date.toLocaleTimeString()}.</h2> </div> ); } } const root = ReactDOM.createRoot(document.getElementById('root')); root.render(<Clock/>);

输出

Hello, world!
It is 10:30:12 AM. //clock is ticking every second.
The clock is now ticking every second.

正确使用状态

您应该了解有关 setState() 的三个方面。

不要直接修改状态

这不会重新渲染组件,例如 −

// Wrong this.state.comment = 'Hello'; Instead, use setState(): // Correct this.setState({comment: 'Hello'});

只有构造函数才能分配 this.state。

状态更新可能是异步的

您不应使用 this.props 和 this.state 的值来确定下一个状态,因为它们可能会被异步修改。例如,在更新计数器时,以下代码不适用 -

// Wrong this.setState({ counter: this.state.counter + this.props.increment, } );

相反,请参考 setState() 的其他版本并使用接受函数的版本。这是因为一些版本将函数视为需要修复的对象。先前的状态将作为该方法的第一个参数传递,而应用更新时存在的 props 将作为第二个参数传递 −

// Correct this.setState((state, props) => ({ counter: state.counter + props.increment } ) );

虽然我们在上面的例子中使用了箭头函数,但普通函数也可以使用 -

// Correct this.setState(function(state, props) { return { counter: state.counter + props.increment }; } );

状态更新已合并

您的状态可能包含许多独立变量 −

constructor(props) { super(props); this.state = { posts: [], comments: [] }; }

此后,您可以使用不同的 setState() 调用分别更新每一个 −

componentDidMount() { fetchPosts().then(response => { this.setState({ posts: response.posts } ); } ); fetchComments().then(response => { this.setState({ comments: response.comments } ); } ); }

this.setState(comments) 完全取代了 this.state.comments,但只是进行了表面合并,而 this.state.posts 保持不变。

因此,状态组件通常被视为本地或包含的。除了拥有和控制它的组件之外,没有其他组件可以访问它。

底线

我们已经讨论了在 React 中向类组件正确添加生命周期方法所需了解的所有内容。由于涉及代码和技术性,许多程序员在执行相同操作时通常会遇到一些困难。因此,请确保正确遵循步骤并在运行命令之前交叉检查代码。


相关文章