search
HomeWeb Front-endJS TutorialWhat do you need to know about React project development? Specific matters for react project development (with examples)

This article mainly talks about what you need to pay attention to when developing react projects. If you want to know, please click in and read it. Let’s read this article together now

对react项目开发,我大概对它的知识点进行了分类,主要由以下几个部分组成。

Basic writing method

Writing method of entry page

import React,{ Component } from 'react';import { render } from 'react-dom';import Main from './components/Main';

render(<Main />,document.getElementById(&#39;app&#39;));

Writing method of component

import React,{ Component } from &#39;react&#39;;
export default class Main extends Component{
    render(){        return (
            <p>
                组件
            </p>
        )
    }
}

Passing value from component

Parent component is passed to child component

父组件传给子组件靠props
import React,{ Component } from &#39;react&#39;;
import { render } from &#39;react-dom&#39;;class Main extends Component{
    render(){        return (
            <p>
                <Child  title="我是父组件"/>
            </p>
        )
    }
}class Child extends Component{
    render(){        return(
            <h2 id="this-props-title">{this.props.title}</h2>
        )
    }
}
render(<Main />,document.getElementById(&#39;app&#39;));

Sub component is passed to parent component

子组件传给父组件靠事件
子组件传递给父组件的过程描述,父组件传递给子组件一个函数,子组件执行这个函数,然后把子组件自己的值可以通过穿参的方式传递进去。然后父组件接受到这个值,进行相应的操作。
import React,{ Component } from &#39;react&#39;;
import { render } from &#39;react-dom&#39;;class Main extends Component{
    constructor(props){        super(props);        this.state = {
            value:&#39;init value&#39;
        }
    }
    render(){        return (
            <p>
                <p>{this.state.value}</p>
                <Child  onClick={(value)=>{this.setState({value:value})}}/>
            </p>
        )
    }
}class Child extends Component{
    render(){        return(
            <button onClick={()=>this.props.onClick("子组件的值")}>点击传值</button>
        )
    }
}
render(<Main />,document.getElementById(&#39;app&#39;));

webpack

webpack的配置一般分为这么几个部分,entry、output、plugin、devServer、module等。

entry告诉webpack入口在哪。
output告诉webpack将来把文件打包到哪。
plugin代表一些其他的操作,如打开浏览器、文件压缩等处理。
devServer代表开发的时候启动一个本地服务器
module代表各种loader用来解析你的代码。

A common webpack configuration file is as follows:

var webpack = require(&#39;webpack&#39;);module.exports = {    entry:"./src/index.js",    output:{        path:&#39;public&#39;,        filename:&#39;bundle.js&#39;
    },    devServer:{        historyApiFallback:true,        hot:true,        inline:true
    },    plugins:[        new webpack.DefinePlugin({            &#39;process.env.NODE.ENV&#39;: "development"
        }),        new webpack.HotModuleReplacementPlugin(),        new OpenBrowserPlugin({            url: &#39;http://localhost:8080&#39;
        })
    ],    module:{        loaders:[{            test:/\.js[x]?$/,            exclude:/node_modules/,            loader:&#39;babel-loader&#39;,            query:{                presets:[&#39;es2015&#39;,&#39;react&#39;,&#39;stage-1&#39;]
            }
        },{            test:/\.css$/,            loaders:[&#39;style&#39;,css]
        },{            test:/\.(png|jpg)$/,            loader:"url-loader"
        }]
    }
}

es6 part

In react, you generally need to know some es6 syntax. For react, some basic usage and writing methods of es6 are listed here.

import and export

import introduces something

import webpack from &#39;webpack&#39;;import React from &#39;react&#39;;import { Component } from &#39;react&#39;;

The variables introduced using "{}" are variables with the same name that must exist in that file.
The variables introduced without using "{}" are the variables thrown by export default in that file, and the variable names can be different.

export throws something.

function a(){    console.log(1);
}let b = 1;export a;export b;export default a;

Export can be thrown multiple times and used multiple times.
Only one export default can be used, which means it will be thrown by default. The essence of

class and extends

class is a keyword that declares a class. Its meaning of existence is the same as var, let, const, function, etc.
How to use:

class Main{}

extends represents inheritance, how to use:

class Main extends Component{}

constructor represents the constructor, and super inherits properties and methods from the parent class.

class Main extends Component{
    constructor(props){        super(props)
    }
}

Life cycle function

Basic life cycle function

Divided into three states

  • Mounting

  • Updating

  • Unmounting


  1. Mounting stage – generally in this stage life cycle function Will only be executed once
    constructor()
    componentWillMount()
    componentDidMount()
    render()

  2. Updating phase – will be executed multiple times
    componentWillReceiveProps()
    shouldComponentUpdate()
    render()
    componentDidUpdate()

  3. Unmountint phase – component unmount period
    componentWillUnmount()
    This is The current component life cycle function. There were previously two life cycle functions called getDefaultProps and getInitialState.
    But their functions are now replaced by constructor.

Component life cycle usage scenarios

  1. constructor
    A common usage method is the initialization of state

    constructor(props){
        super(props);
        this.state = {
            value:&#39;&#39;
        }}
  2. componentWillMount
    Perform some initialization operations. Or do some data loading.
    <br>componentWillMount(){ <br> this.fetchData(); <br>} <br>

  3. ##componentDidMount

    A common scenario is data request

    componentWillMount(){    this.fetchData();
    }

  4. render

    A function that must be included in a react component, returning the dom element of jsx syntax

    render(){    return (
            <p>123</p>
        )
    }

  5. componentWillReceiveProps

    When props are passed, some processing can be performed before rendering. SetState will not be triggered twice.
    There is only one parameter. Represents the props object

  6. shouldComponentUpdate

    There are two parameters, representing props and state
    Must return a true or false. Otherwise, a syntax error will be reported.
    Very useful when performing some performance optimization

  7. componentDidUpdate

    After the component is loaded, perform certain operations

  8. componentWillUnmount

    The most common scenario is to clear the setInterval and setTimeout attached to the component.

    componentWillUnMount(){ <br> clearInterval(this.timer); <br>} <br><br>

  9. ##componentWillReceiveProps analysis
常见的使用场景是,根据传递不同的props,渲染不同的界面数据。
项目比较复杂的情况下,一个页面的值发生变化,就要导致另一个页面的值发生改变,这样需要通过props的方式来告知对方,你的值发生改变。让另外一个组件更新dom。需要使用这个周期函数进行监听接受到的props,从而根据这个props进行相应的数据处理。

shouldComponentUpdate analysis

这个函数的返回值是一个布尔值。返回一个true。
返回一个false的情况下,它的的状态不会进行更新。

Performance optimization part

immutable.js

Data request part

ajax

In react, you can use the traditional XMLHttpRequest object to make data requests.

var xhr = new XMLHttpRequest();

xhr.open(type, url, true);
xhr.onReadyStateChange = ()=>{
if (xhr.readyState == 4 && xhr.status == 200) {
sucess(xhr.responseText);
}
}

promise

promise is the data request method proposed by es6. Currently many browsers have not implemented this yet. But there are polyfills for promise, such as blueBird.js

The basic usage is: Promise object

const Promise = require(`../vendor/bluebird/bluebird.js`);let get = (url,data) => {    return new Promise((resolve, reject) => {        if(res){
            resolve(res);
        }else if(err){
            reject(err);
        }
    })}

fetch

The basic usage of fetch:

 fetch("http://homework.shsoapp.com:80/ttzyservice/task/getTaskSubjectList",{        method: &#39;POST&#39;,        headers: {            &#39;Content-Type&#39;: &#39;application/x-www-form-urlencoded&#39;
        },        mode: &#39;cors&#39;,        body: "page=1&rows=10"
    }).then(res =>{        console.log(res);        return res.json()
    }).then(res => {        console.log(res);
    })

react routing

Basic use

import { BrowserRouter as Router, Link, Route,Switch} from &#39;react-router-dom&#39;;
export default class Main extends Component{
    render(){        return(
            <Router>
                <p>
                    <Switch>
                        <Route path=&#39;/&#39; component={page1}>
                        <Route path=&#39;/home&#39; component={page2}>
                        <Route path=&#39;/age&#39; component={page3}>
                    </Switch>
                </p>
            </Router>
        )
    }
}

Simple and practical use of redux

actions

const ADD_TASK = "ADD_TASK";const ADD_CONTENT = "ADD_CONTENT";

export function addtask(task){
    return {
        type: ADD_TASK,
        task
    }
}
export function addContent(content){
    return {
        type: ADD_CONTENT,
        content
    }
}

reducers

import { addtask,addContent } from &#39;actions&#39;;export function(state = &#39;&#39;,action){
    switch (action.type){        case ADD_TASK:            return action.task;            break;        case ADD_CONTENT:            return action.content;            break;        default:            return state;
    }
}

         

对react项目开发,我大概对它的知识点进行了分类,主要由以下几个部分组成。

Basic writing method

How to write the entry page

import React,{ Component } from &#39;react&#39;;import { render } from &#39;react-dom&#39;;import Main from &#39;./components/Main&#39;;

render(<Main />,document.getElementById(&#39;app&#39;));

How to write the component

import React,{ Component } from &#39;react&#39;;

export default class Main extends Component{
    render(){        return (
            <p>
                组件
            </p>
        )
    }
}

Passing value from component

Passing value from parent component to child component

父组件传给子组件靠props
import React,{ Component } from &#39;react&#39;;
import { render } from &#39;react-dom&#39;;class Main extends Component{
    render(){        return (
            <p>
                <Child  title="我是父组件"/>
            </p>
        )
    }
}class Child extends Component{
    render(){        return(
            <h2 id="this-props-title">{this.props.title}</h2>
        )
    }
}
render(<Main />,document.getElementById(&#39;app&#39;));

Child The component is passed to the parent component

子组件传给父组件靠事件
子组件传递给父组件的过程描述,父组件传递给子组件一个函数,子组件执行这个函数,然后把子组件自己的值可以通过穿参的方式传递进去。然后父组件接受到这个值,进行相应的操作。
import React,{ Component } from &#39;react&#39;;
import { render } from &#39;react-dom&#39;;class Main extends Component{
    constructor(props){        super(props);        this.state = {
            value:&#39;init value&#39;
        }
    }
    render(){        return (
            <p>
                <p>{this.state.value}</p>
                <Child  onClick={(value)=>{this.setState({value:value})}}/>
            </p>
        )
    }
}class Child extends Component{
    render(){        return(
            <button onClick={()=>this.props.onClick("子组件的值")}>点击传值</button>
        )
    }
}
render(<Main />,document.getElementById(&#39;app&#39;));

webpack

webpack的配置一般分为这么几个部分,entry、output、plugin、devServer、module等。

entry告诉webpack入口在哪。
output告诉webpack将来把文件打包到哪。
plugin代表一些其他的操作,如打开浏览器、文件压缩等处理。
devServer代表开发的时候启动一个本地服务器
module代表各种loader用来解析你的代码。

A common webpack configuration file is as follows:

var webpack = require(&#39;webpack&#39;);module.exports = {    entry:"./src/index.js",    output:{        path:&#39;public&#39;,        filename:&#39;bundle.js&#39;
    },    devServer:{        historyApiFallback:true,        hot:true,        inline:true
    },    plugins:[        new webpack.DefinePlugin({            &#39;process.env.NODE.ENV&#39;: "development"
        }),        new webpack.HotModuleReplacementPlugin(),        new OpenBrowserPlugin({            url: &#39;http://localhost:8080&#39;
        })
    ],    module:{        loaders:[{            test:/\.js[x]?$/,            exclude:/node_modules/,            loader:&#39;babel-loader&#39;,            query:{                presets:[&#39;es2015&#39;,&#39;react&#39;,&#39;stage-1&#39;]
            }
        },{            test:/\.css$/,            loaders:[&#39;style&#39;,css]
        },{            test:/\.(png|jpg)$/,            loader:"url-loader"
        }]
    }
}

es6 part

In react, es6 syntax is general You need to know something about react. Some basic usage and writing methods of es6 are listed here.

import and export

import introduces something

import webpack from &#39;webpack&#39;;import React from &#39;react&#39;;import { Component } from &#39;react&#39;;

其中使用“{}”引入的变量是那个文件中必须存在的变量名相同的变量。
不使用“{}”引入的变量是那个文件中export default默认抛出的变量,其中变量名可以不一样。

export抛出一个东西。

function a(){    console.log(1);
}let b = 1;export a;export b;export default a;

其中export可以抛出多个,多次使用。
export default只能使用一个,表示默认抛出。

class和extends

class的本质是一个申明类的关键字。它存在的意义和var、let、const、function等都是一样的。
使用方式:

class Main{}

extends代表继承,使用方式:

class Main extends Component{}

constructor代表构造函数,super是从父类继承属性和方法。

class Main extends Component{
    constructor(props){        super(props)
    }
}

生命周期函数

基本生命周期函数

分三个状态

  • Mounting

  • Updating

  • Unmounting


  1. Mounting阶段–一般在这个阶段生命周期函数只会执行一次
    constructor()
    componentWillMount()
    componentDidMount()
    render()

  2. Updating阶段–会执行多次
    componentWillReceiveProps()
    shouldComponentUpdate()
    render()
    componentDidUpdate()

  3. Unmountint阶段–组件卸载期
    componentWillUnmount()
    这就是现阶段的组件生命周期函数。之前还有两个生命周期函数叫 getDefaultProps 以及 getInitialState。
    但是它们的功能现在被constructor代替。

组件的生命周期使用场景

  1. constructor
    常见的一个使用方式就是state的初始化

    constructor(props){
        super(props);
        this.state = {
            value:&#39;&#39;
        }}
  2. componentWillMount
    进行一些初始化的操作。或者进行一些数据加载。
    <br>componentWillMount(){ <br>    this.fetchData(); <br>} <br>

  3. componentDidMount
    常见场景就是数据请求

    componentWillMount(){    this.fetchData();
    }
  4. render
    一个react组件中必须包含的函数,返回jsx语法的dom元素

    render(){    return (
            <p>123</p>
        )
    }
  5. componentWillReceiveProps
    在props传递的时候,可以在render之前进行一些处理。不会触发二次setState。
    只有一个参数。代表的是props对象

  6. shouldComponentUpdate
    有两个参数,分别代表props和state
    必须返回一个true或者false。否则会语法报错。
    在进行一些性能优化的时候非常有用

  7. componentDidUpdate
    组件加载完毕,进行某些操作

  8. componentWillUnmount
    最常见的场景,对组件附加的setInterval、setTimeout进行清除。
    <br>componentWillUnMount(){ <br>    clearInterval(this.timer); <br>} <br>

componentWillReceiveProps解析

常见的使用场景是,根据传递不同的props,渲染不同的界面数据。
项目比较复杂的情况下,一个页面的值发生变化,就要导致另一个页面的值发生改变,这样需要通过props的方式来告知对方,你的值发生改变。让另外一个组件更新dom。需要使用这个周期函数进行监听接受到的props,从而根据这个props进行相应的数据处理。

shouldComponentUpdate解析

这个函数的返回值是一个布尔值。返回一个true。
返回一个false的情况下,它的的状态不会进行更新。

性能优化部分

immutable.js

数据请求部分

ajax

在react中,可以使用传统的XMLHttpRequest对象进行数据请求。
var xhr = new XMLHttpRequest();
xhr.open(type, url, true);
xhr.onReadyStateChange = ()=>{
   if (xhr.readyState == 4 && xhr.status == 200) {
       sucess(xhr.responseText);
   }
}

promise

promise是es6提出的数据请求方式。目前很多浏览器还没有实现。但是有promise的polyfill,如blueBird.js
基本的使用方式是:Promise对象

const Promise = require(`../vendor/bluebird/bluebird.js`);let get = (url,data) => {    return new Promise((resolve, reject) => {        if(res){
            resolve(res);
        }else if(err){
            reject(err);
        }
    })}

fetch

fetch的基本使用方式:

 fetch("http://homework.shsoapp.com:80/ttzyservice/task/getTaskSubjectList",{        method: &#39;POST&#39;,        headers: {            &#39;Content-Type&#39;: &#39;application/x-www-form-urlencoded&#39;
        },        mode: &#39;cors&#39;,        body: "page=1&rows=10"
    }).then(res =>{        console.log(res);        return res.json()
    }).then(res => {        console.log(res);
    })

react 路由

基本使用

import { BrowserRouter as Router, Link, Route,Switch} from &#39;react-router-dom&#39;;
export default class Main extends Component{
    render(){        return(
            <Router>
                <p>
                    <Switch>
                        <Route path=&#39;/&#39; component={page1}>
                        <Route path=&#39;/home&#39; component={page2}>
                        <Route path=&#39;/age&#39; component={page3}>
                    </Switch>
                </p>
            </Router>
        )
    }
}

redux的简单实用

actions

const ADD_TASK = "ADD_TASK";const ADD_CONTENT = "ADD_CONTENT";

export function addtask(task){
    return {
        type: ADD_TASK,
        task
    }
}
export function addContent(content){
    return {
        type: ADD_CONTENT,
        content
    }
}

reducers

import { addtask,addContent } from &#39;actions&#39;;export function(state = &#39;&#39;,action){
    switch (action.type){        case ADD_TASK:            return action.task;            break;        case ADD_CONTENT:            return action.content;            break;        default:            return state;
    }
}

The above is the detailed content of What do you need to know about React project development? Specific matters for react project development (with examples). For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools