React Notes
# React Core Library and DOM Operations * `react` is the core React library. * `react-dom` is used for DOM-related operations. # React Class Component Inheritance * React class components inherit from `React.Component`. # Virtual DOM * Creating a virtual DOM: * Method: `React.createElement(tagName, properties, children)` * Virtual DOM defined: * A JavaScript object that describes the structure of the view. * Created using `React.createElement`. * An object of type `Object`. * Lighter than real DOM (fewer properties). * Converted by React into a real DOM to be rendered on the page. # React 17 Lifecycle Methods * New lifecycle methods in React 17: `getDerivedStateFromProps`, `getSnapshotBeforeUpdate` # React Project Initialization * Command to initialize a React project: `create-react-app project_name` * Default port for React projects: 3000 # Class Component Render Method * Purpose: Converts the virtual DOM into a real DOM and renders it on the page. # State Updates * Reason for not directly updating state: Calling `setState` triggers the React update lifecycle. # Props in React * Main purpose: Passing values and comd components. # Modifying Props * Props are modified in the parent component. # Props vs. State * Props cannot be modified in the current component, while state can. * State is defined within the component, props are passed from the parent. * Changing state uses `setState`, changing props requires changes in the parent component. * Props are passed to the component (similar to function parameters), state is managed internally (similar to a variable inside a function). # Class vs. Functional Components * When to use class components: When there is complex interactive logic. * When to use functional components: For simple view rendering (cannot use state like class components). * Differences: * Class components have state, functional components are stateless. * Class components have lifecycle methods, functional components do not. * Class components require instantiation, functional components can be directly called, making them more efficient. * Functional components do not bind `this`, `this` is undefined; class components bind `this` to the component instance. * Functional components are typically used for rendering views without much interaction. # Accessing Props * Accessing the `name` prop in functional components: `props.name` * Accessing the `name` prop in class components: `this.props.name` # ShouldComponentUpdate * Purpose of the return value: Controls whether the component should update. * Usage: Used for component performance optimization; decides whether to update based on changes in state and props. * Returns `true` to update, `false` to prevent updating. * `PureComponent` uses this lifecycle method for optimization, achieving high performance. * API to force component update: `this.forceUpdate()` * Preventing rendering without affecting lifecycle execution: Return `false` in `shouldComponentUpdate`. # High-Performance Components * Difference from regular class components: * High-performance components inherit from `PureComponent`, while regular components have `shouldComponentUpdate` default to `true`. * `PureComponent` implements `shouldComponentUpdate` with a shallow comparison of state and props; returns `false` to prevent rendering if they are the same, `true` to allow rendering if different. * Optimization techniques in React: * Use `shouldComponentUpdate` or `PureComponent` for class components; use `React.memo`, `useMemo`, or `useCallback` for functional components. * Prefer functional components for simple rendering without state. # Refs * Ways to create Refs (three methods): * String: `ref="list"` * API: `React.createRef()` * Callback: `ref={(el) => this.inputRef = el}` * Creating Refs in functional vs. class components: * Functional components: Typically use `React.createRef()` as there is no `this`. * Class components: Can use any of the three methods above. # State Lifting * Definition: Moving shared data from multiple parallel or nested components to a common parent/ancestor component for management and dispatch. # SetState * Two ways to write `setState` and their differences: * Object style: `setState({}, () => {})` * Functional style: `setState((state, props) => { return {} }, () => {})` * Object style is syntactic sugar for the functional style; functional style passes `props` and `state` arguments. # CloneElement * Parameters and purpose: * Parameter 1: Virtual DOM or component to clone. * Parameter 2: Configuration properties for the current element; can merge properties. * Parameter 3: Configuration for the current element's children; can override existing children. # React Lifecycle Phases * Three phases: Mounting, Updating, Unmounting * Mounting: * `constructor` (class constructor) * `componentWillMount` (deprecated) * `render` (rendering) * `componentDidMount` (component mounted) * Updating: * `componentWillReceiveProps` (deprecated) * `shouldComponentUpdate` (should component update?) * `componentWillUpdate` (deprecated) * `render` (rendering) * `componentDidUpdate` (component updated) * Unmounting: * `componentWillUnmount` (component will unmount) # ComponentWillMount * Can DOM be manipulated in `componentWillMount`? No. * Reason: The component has not been mounted yet when this lifecycle hook is called. # Component Communication * How to pass parameters between components (at least three ways): * Parent to child, child to parent, cross-level parameter passing. * Parent to Child: * The parent component passes parameters to the child component by binding a custom attribute on the child component's tag. * The value of the custom attribute is the parameter to be passed from the parent component. * The child component receives the value via props. * Child to Parent: * The parent component passes a state-modifying method to the child component. * The child component receives this method through the `props` and passes real parameters. * When the child component triggers this method, the parent component receives the parameters passed from the child component. * Cross-level Parameter Passing Context: * Context API. * Create a context object using `React.createContext()`. This object provides two components: `Provider` and `Consumer`. * Provide data: * `const Con = React.createContext()` * `const { Provider, Consumer } = Con` * Provide data by binding the data needed to be passed on the `value` attribute of the Provider. * Receive data: * The parameter `data` on the callback function of the Consumer component is the received data. # Modifying 'This' Context * Modifying `this` context in React class component functions (three ways): * Using `bind` method: `onClick={this.add.bind(this)}` * Arrow function: `onClick={() => this.add()}` * Configuring in the constructor: `this.add = this.add.bind(this)`, then binding `onClick={this.add}` # JSX * JSX is syntactic sugar for `React.createElement` and is used to create virtual DOM. * Browsers cannot run JSX directly; it needs to be compiled using React tools. * JSX syntax rules (syntax features): * Use `className` instead of `class` for style class names. * Use `htmlFor` instead of `for` attribute. * Add `key` when looping through a list. * Write inline styles using `style={{key: value}}` (e.g., `fontSize` instead of `font-size`). * Only one root tag. * Tags must be closed. * Do not use quotation marks when defining virtual DOM. * Use `{}` when mixing JavaScript expressions in tags. * Advantages of JSX: More concise and closer to native HTML compared to creating virtual DOM with `createElement`. # React Keys * Purpose of keys in React: To update the virtual DOM more efficiently and avoid unnecessary rendering. * Why add key values when looping in React? For efficient virtual DOM updates and to avoid unnecessary rendering. * Why is it not recommended to use index as key values? Adding, reversing, or deleting data can disrupt the order, causing key values to become disordered. * Consequences of using index: Using index as key after data order is disrupted leads to performance degradation. # Synthetic Events * Definition: A React event object that simulates the capabilities of native DOM events, providing better compatibility. * Principle: Event delegation to the document. Synthetic events are not actually bound to a specific element. # React Event Handling * Differences between React element event handling and DOM element event handling: * React uses synthetic events, which are encapsulated native events. * React performs event delegation to the document and uses `event.target` to get the element that triggered the event. * React event names follow camelCase naming convention (e.g., `onClick`, `onChange`). * React events default to the bubbling phase; adding `Capture` to the event name changes it to the capture phase. * `this` inside React events is `undefined` by default unless handled otherwise; arrow functions point to the current component instance. # Deprecated Lifecycle Hooks * Deprecated lifecycle hooks in the old lifecycle (the three "will"s): * `componentWillMount` (instance phase, creation phase) * `componentWillReceiveProps` (component update phase) * `componentWillUpdate` (component update phase) # Mounting Lifecycle Hooks * Lifecycle hooks executed during the instance phase (mount) in the old lifecycle, their purposes, and parameters: * `constructor`: Constructor function. * Purpose: To create an instance object, initialize state, and modify the `this` binding for class member functions. * Parameters: None by default. * `componentWillMount`: Executed before the component is mounted. * Purpose: * Parameters: None by default. * `render`: Converts the virtual DOM to a real DOM and renders it on the page. * Purpose: * Parameters: None by default. * `componentDidMount`: Executed after the component is mounted. * Purpose: To perform initial setup such as starting timers, sending AJAX requests, and subscribing to messages. * Parameters: None by default. # Updating Lifecycle Hooks * Lifecycle hooks executed during the existence phase (update) in the old lifecycle, their purposes, and parameters: * `componentWillReceiveProps`: About to receive props passed down from parent. * Purpose: Can get all custom properties passed from the parent component. * Parameters: Custom properties from the parent. * `shouldComponentUpdate`: Whether the component should update. * Purpose: If true, the component continues to update, otherwise the component stops updating. * Parameters: A custom property and a state. * `componentWillUpdate`: Component will update. * Purpose: Get some information before a component updates and execute some operations. * Parameters: a custom property and a state. * `render`: Convert virtual DOM to real DOM and render to the page. * Purpose: completes rendering. * Parameters: Default no parameters * `componentDidUpdate`: Component is updated. * Purpose: After rendering is complete, get some DOM information * Parameters: A custom attribute; a state; A return value for getSnapshotBeforeUpdate. # Unmounting Lifecycle Hooks * Lifecycle hooks executed during the destruction phase (unMount) in the old lifecycle, their purposes, and parameters: * `componentWillUnMount`: Executed when the component is about to be destroyed. * Function: Close timer, execute unwatch, unbind, unlisten, unsubscribe, etc. * Parameters: Default no parameters # Lifecycle Triggers * Lifecycle hooks triggered by state changes, props changes, and this.forceUpdate in the old lifecycle? * `setState()`: * Trigger is current component's update: * `shouldComponentUpdate` * `componentWillUpdate` * `render` * `componentDidUpdate` * props change: * The props cannot be changed in the current component and are changed by the parent component, and then trigger the update of the subcomponent: * `componentWillReceiveProps` * `shouldComponentUpdate` * `componentWillUpdate` * `render` * `componentDidUpdate` * `this.forceUpdate()`: * `componentWillUpdate` * `render` * `componentDidUpdate` # New Lifecycle Hooks * New lifecycle hooks: * `static getDerivedStateFromProps` * `getSnapshotBeforeUpdate` * `this` point to who in `getDerivedStateFromProps` hook function ? * `this` points to undefined (because it is a static member function and does not belong to any instance) * Which life cycles does `getDerivedStateFromProps` replace? * `componentWillMount` (`getDerivedStateFromProps` is called before `render` during the instance period) * `componentWillReceiveProps` (`getDerivedStateFromProps` is called before `render` when component is updated during the existence period) * (It can be seen from the code example that `getDerivedStateFromProps` can be triggered not only by the update of the parent component, but also by the update of the current component, and `componentWillReceiveProps` can only be triggered by the update of the parent component) * What are the usage scenarios and parameters of `getSnapshotBeforeUpdate`? * Scenario: Get DOM information (e.g. scroll position) before a component update. * Parameter 1: prevProps, props before update * Parameter 2: prevState, state before update * What are the usage conditions for `getSnapshotBeforeUpdate`? * Must have a return value * Used with `componentDidUpdate`, its return value will be passed to `componentDidUpdate` as the third parameter * What is the relationship between `getSnapshotBeforeUpdate` and`componentDidUpdate`? * Coexistence relationship, exist at the same time and use together # Controlled Components * Controlled components defined: The value of a form element is bound to the state. # React Features * React features include: * Declarative design (custom and native components declared the same way). * Efficient use of virtual DOM and DOM diff algorithm to minimize DOM operations. * Flexible with a rich third-party component library support. * JSX, allows flexible DOM creation and JS logic. * Easy creation of custom components. * Unidirectional data flow, makes the data flow of the component system clearer and more controllable. # Vue vs. React * Differences between Vue and React: * React is based on MVC, while Vue is based on MVVM. * React does not have two-way data binding and requires manual implementation of controlled components; Vue's v-model directive implements two-way data binding. * Different underlying principles: React implements its own algorithm; Vue2.0 uses Object.defineProperty to implement data listening; Vue3.0 uses Proxy to implement data listening. * React uses PureComponent and shouldComponentUpdate to optimize components; Vue component dependencies are automatically tracked during rendering. # MVVM vs. MVC * MVC and MVVM defined: M: Model; V: View; C: Controller; VM: ViewModel. * MVVM (Model-View-ViewModel): Refers to the data layer. * View: Refers to the page or component content. * ViewModel: A bridge between view and model is used to implement two-way data binding. * MVC (Model-View-Controller): Model (data layer), view (page or component content), and controller (page business logic, acting as a bridge). * Difference: MVVM is a front-end design pattern derived from MVC. ViewModel extracts the display-related business logic from the Controller. # Unidirectional Data Flow * Understanding unidirectional data flow and its reasons: * Unidirectional data flow regulates the direction of data flow, with level-by-level transmission from the outermost component to the inner component, without reverse transmission. * Reason: To make t systems. # Rendering Rich Text * How to render rich text content in React:`dangerouslySetInnerHTML={{__html:XX}}` # Vue Computed Properties * How to implement a Vue computed property: * ```javascript get m() { return this.state.n } set m(val) { this.setState({n: val}) } handleClick() { m = 100 } render() { return (
{m}
测试) } ```