as the scale of the React application we develop is getting larger and larger, if all the components are still packaged into one bundle file, it may cause the application to load slowly. It is a common practice to package the components in the program into separate files to reduce the load time of the application, which is usually achieved by "loading on demand". In this article, you will learn about the dynamic import of components in React programs. 1.roomnbsp; what is a dynamic import component? dynamic import components refer to loading components when needed, rather than packaging all components into a single bundle file when the application loads. How do we implement it in React? React provides us with a & nbsp; lazy () & nbsp; method and & nbsp; Suspense & nbsp; component, which are the two main tools for dynamically importing components. using & nbsp; React.lazy () , we can easily load components on demand. The syntax is as follows: const MyComponent = React.lazy(() => import('./MyComponent')); in the code above, React.lazy () & nbsp; receives a function that returns a & nbsp; import () & nbsp; function call. import () & the nbsp; function is part of the ECMAScript dynamic import syntax, which allows us to load a module asynchronously at run time. By combining the & nbsp; React.lazy () & nbsp; with the & nbsp; import () & nbsp; function, we can load components on demand. when we use & nbsp; React.lazy () & nbsp;, React automatically wraps the returned component in a & nbsp; lazy…

May 19, 2023 0comments 1484hotness 0likes Aaron Read all

these days we have shared some of React's built-in hook functions, such as useRef, useMemo, useReducer, useImperativeHandle, etc. These built-in hook functions provide great convenience for our development work. In addition to the built-in Hook provided by React, how do we write our own hook functions? Custom Hook allows us to share logic among multiple components, improving code reusability and maintainability. To customize a hook function, we should follow the following rules: Custom Hook must start with use . Custom Hook must be a function, and React's Hook can be used inside the function. Custom Hook must return data or methods. the above three rules must be followed, and they are also mentioned in the official React documentation. Let's use a simple counter example to demonstrate how to customize a general hook function. 1. Define the counter hook function to extract the general logic of a counter into a custom Hook, this hook function should have the following capabilities: can get the value of the current counter; can add value to the counter through the hook function; can reduce the value of the counter through the hook function. based on these three requirements, we can implement the following custom Hook: import { useState } from 'react'; // define the return value type of custom Hook type UseCounterReturnType = [count: number, increment: () => void, decrement: () => void]; // define a custom Hook export default function useCounter(initialCount: number = 0): UseCounterReturnType { // use useState to initialize count state and setCount function const [count, setCount] = useState(initialCount); // define the…

May 18, 2023 0comments 1216hotness 0likes Aaron Read all

Preface friends who know or know Vue all know that in Vue , we can achieve bidirectional data binding of controlled components through v-model , while in React , we need to achieve bidirectional data binding through value and onChange . A single can also be accepted, such as multiple. look at an example. const [nickName, setNickName] = useState('') const [age, setAge] = useState(null) const handleNickNameChange = useCallback((value) => { setNickName(value) }, []) const handleAgeChange = useCallback((value) => { setAge(value) }, []) return ( <> <Input value={nickName} onChange={handleNickNameChange} /> <Input value={age} onChange={handleAgeChange} /> </> ) according to the conclusion above, if there are multiple controlled components in a component, many will be written as above. Can we encapsulate that we only need to declare variables instead of set methods? The answer is OK, you can see below. Tips:input is an uncontrolled component when the value of type is file, because the value is readable when type is file. description what I use here is React + ts . If you use js , you need to delete the type declaration after the variable. withModel the method component I encapsulated here is withModel , which you can name after yourself. //withModel.tsx import React, { forwardRef, useMemo, useCallback, useEffect } from 'react' // two-way binding tool method const withModel = (Component: any) => forwardRef((props, outerRef) => { const p = { models: [], name: '', value: '', onChange: (event: any) => {}, ...props, } const { models = [], name, value, onChange, ...other } = p; const [modelValue, setModelValue] = useMemo(() =>…

May 17, 2023 0comments 1360hotness 0likes Aaron Read all

in the article React developer essential skills: master useReducer foundation and application , we discussed the basic knowledge of useReducer in React. In this article, we will discuss the advanced techniques of useReducer. This article will show you how to flexibly use useReducer to manage complex states within and between components in React programs through a more complex "task control component"-- the core operation component of task processing in TODO applications. implementation ideas in TODO applications, the core operation is the various processing logic of "task", including "add task", "delete task", "filter task", "search task" and so on. To make it easier to understand, we only implement the "add task" and "delete task" logic. at the same time, in order to facilitate us to later maintain and expand the function and logic of the "task" operation, we should package it into a separate component. In addition, the "add task" and "delete task" functions of the component should also be exposed for the parent component to call. subcomponents TaskControl this subcomponent should contain the following functions: use useReducer in the component to manage the task list and use useRef to create a reference to get the value of the input box. wraps the component with forwardRef so that the add task and delete task methods in the component can be called from the parent component. defines functions for add tasks and Delete tasks to update the task list. use useImperativeHandle to expose the add task and delete task functions to the parent component for calling. Let's take a look at the…

May 16, 2023 0comments 1266hotness 0likes Aaron Read all

in React, the management of component state is very important. Typically, we can use useState to manage component state. However, using useState can become very tedious if the state becomes more and more complex. At this point, we can consider using useReducer to manage the state. you might ask, why not use Redux? It is true that Redux is an excellent and popular state management tool, but there are some scenarios where Redux is not the optimal solution. For example, our application is very small, and using Redux at this time may bring additional complexity. Another example is to update the status frequently, which may cause a large number of action to be triggered, which adds additional overhead and complexity. Therefore, for similar scenarios, useReducer might be more appropriate. so how do we correctly apply useReducer ? This article will give you the answer. what is useReducer useReducer is a hook function used to manage the state of components in React. Its function is to decompose the state of the component into multiple values, and to provide a predictable and controllable way to update the state, thus making the code clearer and easier to understand. useReducer is defined as follows: const [state, dispatch] = useReducer(reducer, initialState); useReducer accepts two parameters: reducer : a function that accepts the current state and action (action) , returns the new state . In reducer , you can modify the state according to the type of action . initialState : the initial value of the state. useReducer & the return value of nbsp; is an…

May 16, 2023 0comments 1219hotness 0likes Aaron Read all

the reading time is about 7 minutes. in Web development, we often need to let users download some files, such as PDF, pictures, audio, video, etc. The common way is to have the background server return the file data stream, and then we download it through the download attribute of the a tag. This approach requires background support, but also has some limitations, such as the inability to download cross-domain files. is there a way to download files directly at the front end? the answer is yes, and you can download files at the front end without background service support through the createObjectURL method. this article details how to use createObjectURL to download front-end files in React. according to convention, look at the effect first and then talk about the method ~ createObjectURL method createObjectURL is a method for URL objects to convert binary data or Blob objects into URL that can be used on a page, usually for previewing or downloading files, or to display real-time streaming data from a camera or microphone on a page. The generated URL object can be directly used in the src attribute of media elements such as pictures, audio, video, etc., as well as the link address of the download file. the URL object generated using the URL method is unique and becomes invalid as soon as the page is closed or reloaded. To avoid memory leaks, it is recommended that the URL.revokeObjectURL method be called after use to release it. download text file example Let's take downloading a text file as an…

May 15, 2023 0comments 1321hotness 0likes Aaron Read all

what is cross-domain? Cross-domain is not a problem, it is a security mechanism. The browser has a policy called same origin policy, which stipulates that some requests cannot be accepted by the browser. it is worth mentioning that the cross-domain caused by the same origin policy is that the browser unilaterally refuses to respond to the data, and the server has finished processing and responded. what is homologous policy A url consists of three parts: protocol, domain name (ip address), and port . is called homologous only when the protocol, domain name, and port are the same. the same origin policy states that the browser will accept the response only if the sending side of the request and the receiving side are of the same origin. give me an example Send request address: http:47.96.127.5:8080/index accept request address: http:47.96.127.5:8081/index // different source ports are different Send request address: http:47.96.127.5:8080/index accept request address: http:47.96.127.6:8080/index // different source ip is different Send request address: http:47.96.127.5:8080/index accept request address: https:47.96.127.5:8080/index // different source protocols are different Send request address: http:47.96.127.5:8080/index accept request address: http:47.96.127.5:8080/login // same origin protocol, port, ip are all the same, it doesn't matter if the path is different. Undefined and when our request does not conform to the same origin policy. The following error often occurs: 👇 five common ways to solve cross-domain problems first: JQuery's ajax (recommended for JQuery projects) jq's ajax comes with a cross-domain solution. The underlying principle adopts the cross-domain solution of JSONP. As follows function callback(){ console.log("with a monthly salary of 1500 yuan, my heart…

May 12, 2023 0comments 1315hotness 0likes Aaron Read all

background: when users open the page, they need to render different iterative versions according to the active id of the page. For example, the code used by activity An is v0.0.1 (featureA), and the version used by activity B is v0.0.2 (featureB) of course, the grayscale strategy is not only the active id, but may include the following situations by percentage of traffic by region user id activity id Press ip wait purpose Let product applications be put on the market step by step, find and modify problems step by step, and adapt to the market method: 1. nginx + lua + apollo recommendation index: ⭐️⭐️⭐️⭐️ modify cost: ⭐️⭐️⭐️ specific practice: the user requests nginx,nginx to determine the version that the user needs to render according to the grayscale policy and returns the corresponding version of html. The logic of judging the version is processed by nginx, and the grayscale policy is stored in a database or apollo (such as whitelist ip, whitelist id, percentage value) advantages: does not change the front-end business code, and is easy to maintain disadvantages: the cost of modification is slightly higher, and it requires backend or operation and maintenance support, lua language, and may need to modify the construction process. 2. bff + apollo recommendation index: ⭐️⭐️⭐️ modify cost: ⭐️⭐️⭐️⭐️ specific approach: similar to the first, only nginx is replaced with node.js, which is suitable for projects with bff layer and bff is responsible for rendering front-end pages advantages: does not change the front-end business code, and is easy to maintain disadvantages: for projects…

May 12, 2023 0comments 1252hotness 0likes Aaron Read all

when we use React to build a user interface, one of the most important concepts is status (state). State can be used to store and manage data in React components, and when the state changes, React automatically re-renders the component to reflect the latest state values. React provides the & nbsp; setState & nbsp; function to update the component state, but we need to pay attention to some details when updating the component state using the & nbsp; setState & nbsp; method. In this article, we will gain an in-depth understanding of the role of state updates and callback functions in React, and how to better control state updates. problems with status updates in React, when we update the state using the & nbsp; setState & nbsp; method, React does not guarantee that it will change immediately. Instead, React may batch multiple & nbsp; setState & nbsp; calls together, and then update the status of the component together at some point. This means that if we access the status immediately after updating it, we may get the old value. to avoid this problem, the setState & nbsp; method provides a callback function that allows us to perform some actions after the state update. We can pass the code we want to execute to & nbsp; setState as a callback function, which is called immediately after the status update, so we can make sure that we are accessing the latest state value. For example: this.setState({count: this.state.count + 1}, () => { console.log('Count updated:', this.state.count); }); The code above uses the &…

May 11, 2023 0comments 1496hotness 0likes Aaron Read all

React Hooks is a new feature introduced by React version 16.8 that allows us to use state and other React features without writing class components. Among them, useState and useEffect are the most commonly used. When using React Hooks, because there are no instances of function components, Hooks relies on closures to access and update state. However, when using Hooks, we need to pay attention to the closure trap problem. what is a closure trap? A closure means that a function can access variables defined outside the function. In React, Hooks functions are also closures, and they can access variables defined outside the function. The closure traps of React Hooks are similar to those of ordinary JavaScript, but because of the design of React Hooks, you may encounter some specific problems when using Hooks. Closure traps in React Hooks mainly occur in two situations: use closures in useState; uses closures in useEffect. closure traps in useState closures are used in useState mainly because the parameters of useState are executed only once when the component is mounted. If we use closures in useState, the values of variables in closures are cached, which means that when we update the state in the component, the values of variables in closures are not updated. in the handleClick function, the setCount function returned by useState is used to update the count status value. Because setCount is defined in the App function, and the handleClick function can access the variables and functions defined in the App function, the handleClick function forms a closure that can access…

May 10, 2023 0comments 1469hotness 0likes Aaron Read all