Preface package.json is an important file for describing and configuring a project, which contains a number of fields and options that can affect project construction, dependency management, script execution, and so on. Understanding these fields can help developers better understand and control the behavior of the project. package.json for most front-end developers, knowing dependencies and devDependencies is enough. However, for library developers or developers with more advanced needs, it is necessary to understand the other fields of package.json. the fields introduced in this article are divided into official fields and unofficial fields. Unofficial fields are supported by mainstream packaging tools (webpack,Rollup) and are designed to provide more advanced configuration and functionality to meet specific build needs and may not be universal. current version: v7.24.2 I. required attribute 1. name defines the name of the project, not with "." Start with "_" and cannot contain uppercase letters 2. version defines the version number of the project in the format of large version number. The second edition number. Revision number II. Description information 1. description Project description 2. keywords Project keywords 3. author Project author "author": "name (http://barnyrubble.tumblr.com/)" 4. contributors Project contributor "contributors": [ "name <[email protected]> (http://barnyrubble.tumblr.com/)" ] 5. homepage Project home page address 6. repository Project Code Warehouse address 7. bugs address of project submission question // address for submitting questions and email address for feedback. Url is usually the issues page in Github. "bugs": { "url" : "https://github.com/facebook/react/issues", "email" : "[email protected]" } 8. funding specify the financial support method and link for the project "funding": { "type": "patreon", "url": "https://www.patreon.com/my-module"…

June 20, 2023 0comments 1354hotness 0likes Aaron Read all

We know that useMemo and useCallback are mainly used to cache intermediate states and reduce meaningless render to improve performance. But recently I have found that I have been misunderstanding their use! misunderstanding of useMemo Please take a look at the following code. Even with useMemo , the second subcomponent is re-rendered without the change of isZero ! import { useCallback, useMemo, useState } from "react"; const Child = ({ value, onClick }) => { return ( <div style={{ height: 100, background: `#${(~~(Math.random() * (1 << 24))).toString(16)}` }} > my value is {value.toString()} </div> ); }; export default function App() { const [count, setCount] = useState(0); const isZero = useMemo(() => !!(count % 3), [count]); const onClick = useCallback(() => setCount(count + 1), [count]); return ( <div className="App"> <button onClick={onClick}>click me</button> <Child value={count} /> <Child value={isZero} /> </div> ); } 💡 related reading in fact, the reason has also been mentioned in previous articles: React every time the state of a component changes, it starts from the current component until all leaf node components are re-rendered. The article also mentions the solution to this problem: the subcomponent is wrapped with the memo function, and the component can render as expected. however, at this point we remove useMemo , and the subcomponents are still rendered as expected. memo is similar to useMemo , which is based on a shallow comparison of Object.is and is only valid for non-reference types. so in the above example, it makes no sense to use useMemo . misunderstanding of useCallback however, in the above example, the…

June 6, 2023 0comments 1267hotness 0likes Aaron Read all

Preface this article shows you how to use React and DOM things to achieve a compelling interactive hover box effect. By hovering over the mouse, the box will randomly change the color and display shadows, adding dynamic and visual appeal to the page. Read this article and you'll learn how to use React to implement event handling and dynamic styling, bringing more interesting interactions to your Web application. scene in modern Web applications, interactivity and dynamic effects are critical to improving the user experience. Hovering effect is a common way of user interaction, when the user hovers the mouse over a specific area, the relevant elements will change to attract the user's attention. In this article, we will explore how to use React to implement a CSS special effect of a hover square effect. Let's take a look at → Development first, import React and some necessary hook functions, as well as the stylesheet we will use in the component. As follows: import React, { useEffect, useRef, useState } from 'react'; import './index.less' The code for the index.less file is as follows: .App { background-color: #111; display: flex; align-items: center; justify-content: center; overflow: hidden; margin: 0; } .container { display: flex; align-items: center; justify-content: center; flex-wrap: wrap; max-width: 600px; overflow: hidden; } .square { background-color: #333; box-shadow: 0 0 2px #000; height: 16px; width: 16px; margin: 2px; transition: 2s ease; } .square:hover { transition-duration: 0s; } then defines an array of colors and a constant SQUARES to set the number of squares. As follows: const colors = ['#861104', '#7611a0', '#127ec7',…

June 1, 2023 0comments 1292hotness 0likes Aaron Read all

there have been various disputes over front-end framework for a long time. The most controversial items are the following two: performance dispute dispute over API design for example, emerging frameworks come up with benchmark to prove their excellent runtime performance, and React is usually at the bottom of these benchmark . in the API design, Vue enthusiasts believe that "more API constrains developers and will not cause significant differences in code quality due to differences in the level of team members." and React enthusiasts think: " Vue a large number of API limits flexibility, JSX yyds". the above discussion boils down to the trade-off between framework performance and flexibility. this article introduces a state management library called legendapp , which is very different from other state management libraries in terms of design philosophy. rational use of legendapp in React can greatly improve the runtime performance of the application. but the purpose of this article is not just to introduce a state management library, but to share with you changes in framework flexibility as performance improves. performance optimization of React It is an indisputable fact that the performance of React is really not very good. The reason is the top-down update mechanism of React . with each status update, React traverses the entire component tree first, starting from the root component. since the traversal mode is fixed, how do you optimize performance? The answer is looking for subtrees that can be skipped when traversing . what kind of subtree can skip traversal? Obviously a subtree of that hasn't changed. in React…

May 29, 2023 0comments 1246hotness 0likes Aaron Read all

there are three front-end framework concepts that are easily confused: responsive updates unidirectional data flow Bidirectional data binding before continuing with this article, readers can think about whether they clearly know the meaning of the three. these three are easy to be confused because although they belong to the same front-end framework, they are not the same level of abstraction, so it is difficult to compare them directly. this article will explain the differences between these three levels of abstraction. responsive updates responsive update is also called fine-grained update . At the same time, the recently popular concept of Signal describes responsive updates . In a nutshell, responsive update describes the relationship between state and UI , that is, how state changes map to UI changes . consider the following example (from what are signals article): function TodoApp() { const [todos, setTodos] = useState( [{ text: 'sleep', completed: false }] ) const [showCompleted, setShowCompleted] = useState(false) const filteredTodos = useMemo(() => { return todos.filter((todo) => !todo.completed || showCompleted) }, [todos, showCompleted]) return ( <TodoList todos={filteredTodos} /> ) } in the TodoApp component, two states are defined: to-do todos whether to show completed items showCompleted and the state derived from the above state filteredTodos . Finally, the & lt;TodoList/> component is returned. if the state of todos changes, how does UI change? That is, how do we know the scope of influence of state changes ? At this point, there are two ideas: push ( push ) pull ( pull ) the principle of push We can start with the changing…

May 27, 2023 0comments 1208hotness 0likes Aaron Read all

Preface recently started a new project, want to do a good job of code specifications and constraints, in fact, there are a lot of scaffolding, project templates can be used directly, but do-it-yourself, can be completely self-matching. install eslint install and execute yarn add-- dev eslint add .eslintrc.js to the project directory module.exports = { root: true, // specify root as true,eslint to check only the current project directory env: { // provide default global variables to prevent eslint from checking for errors, such as window browser: true, node: true, es6: true, }, extends: [ // inherit the inspection rules recommended by eslint 'eslint:recommended', ], parserOptions: { ecmaVersion: 'latest', // specify the ECMAScript syntax as up-to-date sourceType: 'module', // specify the code as ECMAScript module ecmaFeatures: { jsx: true, // enable jsx }, }, }; add .eslintignore to the project directory, ignoring some directories and files that do not require eslint detection .eslintrc.js node_modules dist .DS_Store *.local install typescript-eslint since the project uses Typescript , you need to change the eslint interpreter. Refer to typescript-eslint . install and execute yarn add-- dev @ typescript-eslint/parser @ typescript-eslint/eslint-plugin change .eslintrc.js module.exports = { root: true, // specify root as true,eslint to check only the current project directory env: { // provide default global variables to prevent eslint from checking for errors, such as window browser: true, node: true, es6: true, }, extends: [ // share the recommended configuration style 'eslint:recommended', 'plugin:@typescript-eslint/recommended', ], parser: '@typescript-eslint/parser', plugins: ['@typescript-eslint'], parserOptions: { ecmaVersion: 'latest', // specify the ECMAScript syntax as up-to-date sourceType: 'module', // specify the…

May 1, 2023 0comments 1513hotness 0likes Aaron Read all

recently, t3dotgg, a foreign netizen, suggested that React officially use Create React App to create a new project instead of in the document . It is recommended to use Vite to create a new project . Most netizens agree with this: React's new official document is about to be released (99% is now complete). However, Create React App is still recommended in the Beta version of the official document to create a new project. Two additional alternatives are provided: Vite , Parcel . looking at Create React App's Github repository, we can see that it has not been updated for 5 months, accumulating 1500 + issues . on January 31, Dan Abramov, a core member of the React team, responded to this suggestion, explaining the tradeoffs made by React team members and providing some options. Let's take a look at the details (you can skip to the final conclusion)! Evolution of Create React App when Create React App was released in 2016, the environment of the tool was decentralized. If you want to add React to an existing application, you need to add a & lt;script> tag or import from npm, and then adjust the existing build tool configuration. However, if you want to create a new application built only using React from scratch, there is no clear way to do this. before Create React App, you must install a bunch of tools and connect them together, provide correct presets to use JSX, make different configurations for development and production environments, provide correct settings for resource caching, configure linter, etc.,…

May 1, 2023 0comments 1525hotness 0likes Aaron Read all

8 Mock.js installation and use in the process of development, in order to make it easier for the front end to debug the interface alone, Mock.js is often used to intercept Ajax requests and return preset data. This section describes how to use Mock.js in a react project. perform installation: npm install mockjs --save create a new mock.js under src, as follows: import Mock from 'mockjs' const domain = '/api/' // Simulating the getData interface Mock.mock(domain + 'getData', function () { let result = { code: 200, message: 'OK', data: 'test' } return result }) then introduce mock.js: into src/index.js import React from 'react' import ReactDOM from 'react-dom' import App from './App' import { Provider } from 'react-redux' import store from './store' + import './mock' import './common/style/frame.styl' ...(summary) it's so simple. In this way, when a / api/getData is requested in a project, it is intercepted by Mock.js and the data written in mock.js is returned. 9 solve the cross-domain problem of local development in the react development environment, port 3000 is started by default, while the back-end API service may be on port 80 of the machine, so cross-domain problems may occur during ajax requests. Reverse proxy can be implemented with the help of http-proxy-middleware tools. perform installation: npm install http-proxy-middleware --save-dev create a setupProxy.js under src, as follows: const proxy = require('http-proxy-middleware'); module.exports = function (app) { app.use( '^/api', proxy({ target: 'http://localhost', changeOrigin: true }) ) } this code means that as long as the request address starts with "/ api", it will reverse proxy to the http://localhost…

April 26, 2023 0comments 1442hotness 0likes Aaron Read all

the relative basics of the React project have been explained in detail in 1BI 2 of this tutorial. In 3pr 4, continue to explain the advanced part of React. Build the whole family bucket of React project from scratch (1) Build the whole family bucket of React project from scratch (2) before we begin, review the content introduced in the previous article: 1 create React-APP 2 streamlined items 2.1 Delete files 2.2 simplify the code 2.3 use Fragment to remove the outer tag of the component 3 Project directory structure 3.1 introduce global common styles 3.2 support Sass/Less/Stylus 4 routes 4.1 Page build 4.2 use react-router-dom 4.3 Route Jump 5 components introduce 5.1 create header components 5.2 introduce Header components 5.3 components pass parameters 6 React Developer Tools browser plug-in in this second article, continue to share the following: take a peek at it 7 Redux and related plug-ins 7.1 install redux 7.2 install react-redux 7.3 install redux-thunk 7.4 install the browser Redux plug-in 7.5 create store 7.6complex project store decomposition 7.7 docking react-redux with store 7.8 start Redux DevTools 7.9 install using immutable 8 Mock.js installation and use 9 solve the cross-domain problem of local development 10 other commonly used tools 11 complimentary chapter: integrated Ant Design 11.1 install Ant Design 11.2 implement on-demand loading 11.3 Custom theme colors 7 Redux and related plug-ins students who have done vue development know that the corresponding tool for vuex,react is Redux, and of course there are some ancillary tools, such as react-redux, redux-thunk, and immutable. redux involves a lot of content…

April 26, 2023 0comments 1226hotness 0likes Aaron Read all

4 routes 4.1 Page build first, build the home and login pages. src/pages/home/index.js Code: import React, { Component } from 'react' import './home.styl' class Home extends Component { render() { return ( <div className="P-home"> <h1>Home page</h1> </div> ) } } export default Home src/pages/home/home.styl Code .P-home h1 padding: 20px 0 font-size: 30px color: #fff background: #67C23A text-align: center src/pages/login/index.js Code: import React, { Component } from 'react' import './login.styl' class Login extends Component { render() { return ( <div className="P-login"> <h1>Login page</h1> </div> ) } } export default Login src/pages/login/login.styl Code .P-login h1 background: #E6A23C my personal habit is for reference only: className at the global public level (no modularization is required), using G-xxx. For example, G-autocut (truncation), G-color-red (text red). page-level className, using P-xxx. module-level className, using M-xxx. Next, we use react-router-dom to implement routing. 4.2 use react-router-dom execute the installation command: npm install react-router-dom --save modify src/App.js, the code is as follows: import React, { Fragment } from 'react' import Login from './pages/login' import Home from './pages/home' import { HashRouter, Route, Switch, Redirect } from 'react-router-dom' function App() { return ( <Fragment> <HashRouter> <Switch> <Route path="/login" component={Login} /> <Route path="/home" component={Home} /> <Route exact path="/" component={Home} /> <Redirect to={"/home"} /> </Switch> </HashRouter> </Fragment> ) } export default App App.js introduces two page-level components, Home and Login. Then the paths are set using react-router-dom. The mechanism of import is to find index.js by default, so the primary file name of each component is set to index.js, which can be omitted when referenced. explain the attributes of & lt;Route> here:…

April 25, 2023 0comments 1381hotness 0likes Aaron Read all
12