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 1361hotness 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 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 1321hotness 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

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

in the daily development of the team, people write components of different quality and styles, and there are many ways of naming them. For example, some use tags as component names, but I won't say who they are. Components cannot be extended or difficult to maintain because of many requirements. It is quite difficult to reuse the functions of many business components. so in today's article we'll talk about how to set up an elegant React component in terms of component design patterns. basic principles of component design when designing a high-quality component or a set of high-quality components, we should first follow the following principles, including the following aspects. single responsibility the principle of single responsibility is to make a module focus on a Phoenix girl, that is, to minimize the responsibility of a module. If a module has too many functions, it should be divided into multiple modules, which is more conducive to the maintenance of the code. A single component is easier to maintain and test, but don't abuse it, split components if necessary, minimize granularity at one extreme, and may result in a large number of modules, and module discretization can make the project difficult to manage. demarcate boundaries how to split components, if the two components are too closely related to logically clearly define their respective responsibilities, then the two components should not be split. Otherwise, if their respective responsibilities are not clear and the boundaries are not distinct, the problem of logical confusion will arise. Then the most important thing to split the components…

May 8, 2023 0comments 1270hotness 0likes Aaron Read all

let's start with some nonsense I remember this hooks very well, because at that time, during an interview, I was asked to implement this custom hooks by hand, , so it was prepared for the first hooks in this series. to see the effect when our component becomes complex, do you want to know what caused the component to render, or what the value change is, this hooks will solve your problem. here comes the hooks source code type IProps = Record<string, unknown>; / * * * what caused the page render to customize hooks * *@paramName of the componentName observation component *@paramData that props needs to observe (data such as current component state or incoming props that may cause rerender) , / const useWhyDidYouUpdate = (componentName: any, props: any) => { // create a ref object let oldPropsRef = useRef<IProps>({}); useEffect(() => { if (oldPropsRef.current) { // iterate through all the key of the old and new props let keys = Object.keys({ ...oldPropsRef.current, ...props }); // change the information object let changeMessageObj: IProps = {}; keys.forEach((key) => { // compare whether the new and old props are changed, changed and recorded to changeMessageObj if (!Object.is(oldPropsRef.current[key], props[key])) { changeMessageObj[key] = { from: oldPropsRef?.current[key], to: props[key], }; } }); // whether there is change information, existence and printing if (Object.keys(changeMessageObj).length) { console.log(componentName, changeMessageObj); } // Update ref oldPropsRef.current = props; } }); }; demo complete source code import React, { useState, useRef, useEffect } from 'react'; import { Button, Statistic } from 'antd'; type IProps = Record<string, unknown>; / * *…

May 8, 2023 0comments 1361hotness 0likes Aaron Read all
1…45678…10