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

Preface in the react project, we usually use the axios library, which is a promise-based http library, to interact with the background to obtain data. It can be run on the browser side and in node.js. It has many excellent features, such as intercepting requests and responses, canceling requests, converting json, client defense XSRF, and so on. install / / install using npm Npm install axios / / install using yarn Yarn add axios Undefined introduce in the project root, create a new request folder, and then create a new index.js and an api.js file in it. The index.js file is used to encapsulate our axios,api.js to uniformly manage our interface. / / introduce axios into index.js import axios from 'axios'; / / introduce qs module to serialize data of type post import QS from 'qs'; / / message prompt component of antd, which can be changed according to your own ui component. import { message } from 'antd' switching of environment our project environment may have a development environment, a test environment and a production environment. We match our default interface url prefix through the environment variable of node. Here you need the global variable process of node, and process.env.NODE_ENV to distinguish between a development environment and a production environment. / / Save environment variables const isPrd = process.env.NODE_ENV == 'production'; / / distinguish the basic URL of development environment or production environment export const basciUrl = isPrd ? 'https://www.production.com' : 'http://www.development.com' the basic URL is exported here to prevent resources from being used differently in other places, and…

April 30, 2023 0comments 1450hotness 0likes Aaron Read all

introduction to Axios Axios is a promise-based HTTP library that can be used in browsers and node.js. Features supports node side and browser side supports advanced configurations such as interceptors use Promise to manage asynchrony, bid farewell to traditional callback mode automatically convert JSON data client supports defense of XSRF install yarn installation $ yarn add axios npm installation npm install axios -D 3.bower installation $ bower install axios easy to use aixos can be loaded directly through cdn, for example: <html> <head> <title>The use of Axios</title> <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.19.2/axios.js"></script> </head> <body> <input type="button" onclick="getList()" value="Click get"/> <div id="content"> </div> <script type="text/javascript"> function getList(){ axios.request({ url:'/article/home/index', method:'get', baseURL:'http://test.mediastack.cn/' }).then( res => { console.log("get res:",res); var str=JSON.stringify(res); document.getElementById("content").innerHTML = str; },error => { console.log("get request failed:",error); document.getElementById("content").innerHTML = error; } ); } </script> </body> </html> axios is encapsulated in react Axios can be encapsulated into a file in react. Through control operations, unified handling of errors, logic, and validation can be achieved, reducing the redundancy and readability of the code. request encapsulation / * * * Network request configuration , / import axios from "axios"; axios.defaults.timeout = 100000; axios.defaults.baseURL = "http://test.mediastack.cn/"; / * * * http request interceptor , / axios.interceptors.request.use( (config) => { config.data = JSON.stringify(config.data); config.headers = { "Content-Type": "application/json", }; return config; }, (error) => { return Promise.reject(error); } ); / * * * http response interceptor , / axios.interceptors.response.use( (response) => { if (response.data.errCode === 2) { console.log("out of date"); } return response; }, (error) => { console.log("request error:", error); } ); / * * * encapsulate the…

April 30, 2023 0comments 1456hotness 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

this article is used to record some of the author's gains in the section strict mode in the official React18 documentation, concerning the role of strict mode, why React executes useEffect twice, and how to optimize it. strict mode (Strict Mode) what is strict mode strict mode is a tool to check for possible problems in your application. Strict mode only runs in a development environment, but it has no impact in a production environment. import React from 'react'; function ExampleApplication() { return ( <div> <Header /> <React.StrictMode> <div> <ComponentOne /> <ComponentTwo /> </div> </React.StrictMode> <Footer /> </div> ); } you can use React.StrictMode to wrap the apps you want to check. Apps without packages will not be affected. For example, the & lt;Header / & gt; component in the above code will not be affected by the strict mode, only the & lt;ComponentOne / & gt; and & lt;ComponentTwo> that we package will be affected by the strict mode. the role of strict mode strict mode makes the following checks identify unsafe lifecycles, such as componentWillMount. Later, it was upgraded to componentDidMount check on ref, a previous version of API, I hope you can replace it with a new version warning of findDOMNode being deprecated detect unexpected side effects found API with expired context ensure reusable state ReactThe official document of React provides an example, which should mean that if we jump from Route A to Route B and then return from Route B. ReactI hope to immediately display the original state, so that I can cache the state…

April 20, 2023 0comments 1623hotness 0likes Aaron Read all

import { Switch, Route, Router } from 'react-router'; import { Swtich, Route, BrowserRouter, HashHistory, Link } from 'react-router-dom'; 1, api React-router: provides the core api of the route. Such as Router, Route, Switch, etc., but does not provide api; for routing redirection for dom operations React-router-dom: provides api such as BrowserRouter, Route, Link, etc., which can trigger events to control routing through dom actions. Link component, which renders an a tag; BrowserRouter, which uses pushState and popState events to build routes, and HashRouter components, which use hash and hashchange events to build routes. 2, dynamic route hopping React-router: this.props.history.push ('/ path') above router4.0 to jump; this.props.router.push ('/ path') above router3.0 to jump; React-router-dom: use this.props.history.push ('/ path') to jump directly 3, differences in use react-router-dom extends the api of operable dom on the basis of react-router. both Swtich and Route import the corresponding components from react-router and re-export them without any special treatment. there is a dependency on react-router in the package.json dependency in react-router-dom, so there is no need for npm to install react-router. you can install react-router-dom directly with npm and use its api.

April 20, 2023 0comments 1728hotness 0likes Aaron Read all

functional programming from Immutable.js to Redux basic concepts functional programming (English: functional programming), or functional programming or functional programming, is a programming paradigm. It treats computer operations as functional operations and avoids the use of program states and mutable objects. Among them, λ calculus is the most important foundation of the language. Moreover, the function of the λ calculus can accept the function as the input parameter and the output return value. the above is Wikipedia's definition of functional programming, which can be summed up in simple words as " emphasizes the function-based software development style ". in addition to the abstract definition, JS's functional programming has the following characteristics: function is a first-class citizen embrace Pure function , reject side effects use immutable values functional programming elements The function is a first-class citizen We often hear the saying, "in JS, a function is a first-class citizen". Its specific meaning is that the function has the following characteristics: can be passed to other functions as arguments can be used as the return value of another function can be assigned to a variable functional first-class citizenship is a must for all functional programming languages, while another must-have feature is support for closures (the second point above actually uses closures a lot of times) Pure function have and only display data streams: input: parameter output: return value if a function is pure, it should conform to the following points: there can be no side effects inside the function for the same input (parameter), you must get the same output. this means that…

April 17, 2023 0comments 1366hotness 0likes Aaron Read all
123456