我的 React 之旅始于四年前的函数式组件和 Hook。然后是“Siswe”,他是训练营的参与者,也是我们常驻班的组件爱好者。当我们其他人在使用功能组件的团队项目上进行协作时,“Siswe 坚定不移地忠诚于类组件。
组件是用户界面 (UI) 的构建块。
将它们视为乐高积木 - 您可以以各种方式组合它们来创建复杂的结构。它们是独立且可重用的代码片段,封装了 UI 和逻辑。
在另一个组件中重用一个组件通常如下所示:
import MyComponent from './MyComponent'; function ParentComponent() { return ( <div> <mycomponent></mycomponent> </div> ); }
类组件和功能组件是在 React 中创建组件的两种主要方式。
import React, { Component } from 'react'; class Counter extends Component { constructor(props) { super(props); this.state = { count: 0 }; } handleClick = () => { this.setState({ count: this.state.count + 1 }); }; render() { return ( <div> <p>You clicked {this.state.count} times</p> <button onclick="{this.handleClick}">Click me</button> </div> ); } } export default Counter;
这是一个类组件,使用扩展 React.Component 类的 JavaScript 类创建。
import React, { useState } from 'react'; function Counter() { const [count, setCount] = useState(0); const handleClick = () => { setCount(count + 1); }; return ( <div> <p>You clicked {count} times</p> <button onclick="{handleClick}">Click me</button> </div> ); } export default Counter;
另一方面,这是一个函数组件,编写为简单的 JavaScript 函数。
状态管理:核心区别。
类组件使用 this.state 管理自己的内部状态。这通常在构造函数中初始化,使用 this.state 对象访问,并使用 this.setState 方法更新,如上面的代码块所示。
功能组件最初是无状态的。但随着 Hooks 的引入,他们获得了管理状态和生命周期逻辑的能力。利用 useState 挂钩来管理状态,它返回一对值:当前状态和更新它的函数,如上所示。这对于简单的状态管理来说已经足够了。对于涉及多个子值的更复杂的状态逻辑,或者当下一个状态依赖于前一个状态时,您需要使用 useReducer。
例如:
import React, { useReducer } from 'react'; const initialState = { count: 0, step: 1, }; const reducer = (state, action) => { switch (action.type) { case 'increment': return { ...state, count: state.count + state.step }; case 'decrement': return { ...state, count: state.count - state.step }; case 'setStep': return { ...state, step: action.payload }; default: throw new Error(); } }; function Counter() { const [state, dispatch] = useReducer(reducer, initialState); const increment = () => dispatch({ type: 'increment' }); const decrement = () => dispatch({ type: 'decrement' }); const setStep = (newStep) => dispatch({ type: 'setStep', payload: newStep }); return ( <div> <p>Count: {state.count}</p> <p>Step: {state.step}</p> <button onclick="{increment}">+</button> <button onclick="{decrement}">-</button> <input type="number" value="{state.step}" onchange="{(e)"> setStep(Number(e.target.value))} /> </div> ); } export default Counter;
这里,useReducer 以结构化且可维护的方式管理多个状态值和复杂的更新逻辑。 Hooks 专门用于功能组件。
避免直接操作两个组件中的状态对象。
无论组件类型如何,都不要直接修改或改变状态对象。相反,使用更新的值创建一个新对象。这种方法有助于 React 有效地跟踪更改并优化重新渲染。
功能组件示例:
import React, { useState } from 'react'; function UserProfile() { const [user, setUser] = useState({ name: 'Jane Doe', age: 30 }); const handleNameChange = (newName) => { setUser({ ...user, name: newName }); // Create a new object with updated name }; return ( <div> <p>Name: {user.name}</p> <p>Age: {user.age}</p> <input type="text" value="{user.name}" onchange="{(e)"> handleNameChange(e.target.value)} /> </div> ); } export default UserProfile;
类组件示例:
import React, { Component } from 'react'; class UserProfile extends Component { state = { user: { name: 'Jane Doe', age: 30 } }; handleNameChange = (newName) => { this.setState(prevState => ({ user: { ...prevState.user, name: newName } // Create a new object with updated name })); }; render() { return ( <div> <p>Name: {this.state.user.name}</p> <p>Age: {this.state.user.age}</p> <input type="text" value="{this.state.user.name}" onchange="{(e)"> this.handleNameChange(e.target.value)} /> </div> ); } } export default UserProfile;
在这两个示例中,我们都在更新用户对象的 name 属性,同时保留原始对象的完整性。这确保了创建新的状态对象,保持不变性并防止状态更新的潜在问题。遵守这一点可确保可预测的行为、性能优化和更轻松的调试。
Class components are for complex logic.
- Complex State Management: When dealing with intricate state logic that requires fine-grained control, class components with this.state and this.setState can offer more flexibility.
- Lifecycle Methods: For components that heavily rely on lifecycle methods like componentDidMount, componentDidUpdate, or componentWillUnmount, class components are the traditional choice.
- Error Boundaries: To handle errors within a component tree and prevent crashes, class components with componentDidCatch are essential.
- Performance Optimization: In specific performance-critical scenarios, PureComponent or shouldComponentUpdate within class components can be leveraged.
- Legacy Codebases: If you're working on an existing project that heavily relies on class components, it might be easier to maintain consistency by using them for new components.
Functional components are for simple views.
- Simple Components: For presentational components with minimal state or logic, functional components are often the preferred choice due to their simplicity and readability.
- State Management with Hooks: Leveraging useState and useReducer in functional components provides a powerful and flexible way to manage state.
- Side Effects: The useEffect hook allows for managing side effects like data fetching, subscriptions, or manual DOM (document object model) manipulations.
- Performance Optimization: useMemo and useCallback can be used to optimize performance in functional components.
Let your component's needs guide your decision.
The functional approach is generally considered more concise and readable, and it often suffices due to simplicity and efficiency. However, class components offer more control over state management and lifecycle methods, especially when dealing with intricate logic or performance optimization. This means better structure for organizing complex logic.
The choice between class and functional components is not always clear-cut, as there is no strict rule. Evaluate the requirements of your component and go with the type that aligns best with your project requirements.
Which component do you enjoy working with more?
以上是React 组件:类与函数式。的详细内容。更多信息请关注PHP中文网其他相关文章!

Python更适合初学者,学习曲线平缓,语法简洁;JavaScript适合前端开发,学习曲线较陡,语法灵活。1.Python语法直观,适用于数据科学和后端开发。2.JavaScript灵活,广泛用于前端和服务器端编程。

Python和JavaScript在社区、库和资源方面的对比各有优劣。1)Python社区友好,适合初学者,但前端开发资源不如JavaScript丰富。2)Python在数据科学和机器学习库方面强大,JavaScript则在前端开发库和框架上更胜一筹。3)两者的学习资源都丰富,但Python适合从官方文档开始,JavaScript则以MDNWebDocs为佳。选择应基于项目需求和个人兴趣。

从C/C 转向JavaScript需要适应动态类型、垃圾回收和异步编程等特点。1)C/C 是静态类型语言,需手动管理内存,而JavaScript是动态类型,垃圾回收自动处理。2)C/C 需编译成机器码,JavaScript则为解释型语言。3)JavaScript引入闭包、原型链和Promise等概念,增强了灵活性和异步编程能力。

不同JavaScript引擎在解析和执行JavaScript代码时,效果会有所不同,因为每个引擎的实现原理和优化策略各有差异。1.词法分析:将源码转换为词法单元。2.语法分析:生成抽象语法树。3.优化和编译:通过JIT编译器生成机器码。4.执行:运行机器码。V8引擎通过即时编译和隐藏类优化,SpiderMonkey使用类型推断系统,导致在相同代码上的性能表现不同。

JavaScript在现实世界中的应用包括服务器端编程、移动应用开发和物联网控制:1.通过Node.js实现服务器端编程,适用于高并发请求处理。2.通过ReactNative进行移动应用开发,支持跨平台部署。3.通过Johnny-Five库用于物联网设备控制,适用于硬件交互。

我使用您的日常技术工具构建了功能性的多租户SaaS应用程序(一个Edtech应用程序),您可以做同样的事情。 首先,什么是多租户SaaS应用程序? 多租户SaaS应用程序可让您从唱歌中为多个客户提供服务

本文展示了与许可证确保的后端的前端集成,并使用Next.js构建功能性Edtech SaaS应用程序。 前端获取用户权限以控制UI的可见性并确保API要求遵守角色库

JavaScript是现代Web开发的核心语言,因其多样性和灵活性而广泛应用。1)前端开发:通过DOM操作和现代框架(如React、Vue.js、Angular)构建动态网页和单页面应用。2)服务器端开发:Node.js利用非阻塞I/O模型处理高并发和实时应用。3)移动和桌面应用开发:通过ReactNative和Electron实现跨平台开发,提高开发效率。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

ZendStudio 13.5.1 Mac
功能强大的PHP集成开发环境

PhpStorm Mac 版本
最新(2018.2.1 )专业的PHP集成开发工具

Dreamweaver CS6
视觉化网页开发工具

VSCode Windows 64位 下载
微软推出的免费、功能强大的一款IDE编辑器

Dreamweaver Mac版
视觉化网页开发工具