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 1267hotness 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 1220hotness 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 1322hotness 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 1317hotness 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 1497hotness 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 1470hotness 0likes Aaron Read all

recently, in the process of promotion in the department, I encountered a question and answer session about front-end security, and I felt that I was lack of knowledge. Here is a summary of my learning experience. This paper summarizes the security strategies that you need to master as a front-end engineer. XSS XSS (Cross Site Scripting) is called a cross-site scripting attack, which uses the privileges of the logged-in user to inject a script into the page to fake the user's request backend. scenario of being attacked pages with unsafe form input Promotion of unknown links or pop-up window use ID theft tamper with, steal and delete enterprise information data illegal transfer DDos attacks on others using host ... attack type reflective XSS script is hidden in the connection, and after deceiving the user to click, it will execute the hacker's script, or take advantage of the loophole in the blog site to enter the attack script in the input box and trigger the user to click or access passively. Storage XSS scripts (for example: & lt;script>alert (document.cookie) & lt;/script> ) are stored on the server, such as online blogs, and the hacker script is executed every time the data is read from the server or when the user is induced to click after rendering. an example of storage + reflection is as follows: when you fill in the form and save it, when you open it for editing again, there will be not only a value field in the input, but also an additional onckick event. Each time you…

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

single data binding in Vue, two-way data binding can be achieved through the v-model instruction. However, there is no concept of instructions in React, and React does not support bidirectional data binding by default. React only supports the transfer of data from the state to the page, but it cannot automatically transfer the data from the page to the state for storage. In React, only single data binding is supported, not bidirectional data binding. If you don't believe me, let's look at the following example: import React from "react"; export default class MyComponent extends React.Component { constructor(props) { super(props); this.state = { msg: "this is the default msg for MyComponent components" }; } render() { return ( <div> <h3>Test component</h3> <input type="text" value={this.state.msg} /> </div> ); } } In the code above, we try to read the value of state.msg in the input text box, but a warning pops up in the run result: Warning: Failed prop type: You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultValue`. Otherwise, set either `onChange` or `readOnly`. Bidirectional data binding is implemented through the onChange method if you bind value attributes to a form element, you must also bind readOnly for the form element, or provide the onChange event: if you bind readOnly, it means that the element is read-only and cannot be modified. At this point, the console will not pop up a warning. if you are binding onChange, it means that the value of…

May 9, 2023 0comments 1296hotness 0likes Aaron Read all

Let's start with some nonsense useUpdateEffect & nbsp; usage is equivalent to & nbsp; useEffect , but ignores execution for the first time, only if it depends on updates. there are scenarios in which we do not want to perform effect when rendering for the first time, such as when searching, the search method is called only when the keyword changes. This hooks is also used more often in daily work, so it is necessary for us to write its source code, 🤓. Let's see the effect for the first time, only useEffect prints count, and only when count changes, useUpdateEffect prints count Source code implementation import React, { useEffect, useRef } from 'react'; const useUpdateEffect = ( effect: React.EffectCallback, deps: React.DependencyList, ) => { let isFirst = useRef(true); useEffect(() => { if (isFirst.current) { isFirst.current = false; return; } return effect(); }, [deps]); }; complete demo source code import React, { useEffect, useRef } from 'react'; import { Button } from 'antd'; const useUpdateEffect = ( effect: React.EffectCallback, deps: React.DependencyList, ) => { let isFirst = useRef(true); useEffect(() => { if (isFirst.current) { isFirst.current = false; return; } return effect(); }, [deps]); }; const Demo = () => { const [count, setCount] = React.useState(0); useEffect(() => { console.log('count' of useEffect, count); }, [count]); useUpdateEffect(() => { console.log('count' of useUpdateEffect, count); }, [count]); return ( <> <div>Count: {count}</div> <Button type="primary" onClick={() => setCount(count + 1)}> Click me + 1 </Button> </> ); }; export default Demo; reference interested friends can look at the source code of react-use and ahooks to…

May 9, 2023 0comments 1371hotness 0likes Aaron Read all
15678912