搜尋
首頁web前端js教程React專案開發你需要知道哪些? react專案開發具體事項(附實例)

本篇文章主要的講述了關於react專案開發需要注意的哪些情況,想知道的同學就趕緊點進來看吧,現在就一起來閱讀本篇文章吧

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

基礎寫法

#入口頁面的寫法

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

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

元件的寫法

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

元件傳值

#父元件傳給子元件

父组件传给子组件靠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;));

子元件傳給父元件

子组件传给父组件靠事件
子组件传递给父组件的过程描述,父组件传递给子组件一个函数,子组件执行这个函数,然后把子组件自己的值可以通过穿参的方式传递进去。然后父组件接受到这个值,进行相应的操作。
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用来解析你的代码。

一個普通的webpack設定檔如下:

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部分

在react 中,es6語法一般是要會一些的,針對react,關於es6一些基本的使用以及寫法,這裡列出來。

import和export

import引入一個東西

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

    進行一些初始化的操作。或進行一些資料載入。

    componentWillMount(){ <br> this.fetchData(); <br>} <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進行清除。

    componentWillUnMount(){ <br> clearInterval(this.timer); <br>} <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;
    }
}

           

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

入口頁面的寫法

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;));

元件的寫法

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

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

元件傳值

父元件傳給子元件

父组件传给子组件靠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;));

子元件傳給父元件

子组件传给父组件靠事件
子组件传递给父组件的过程描述,父组件传递给子组件一个函数,子组件执行这个函数,然后把子组件自己的值可以通过穿参的方式传递进去。然后父组件接受到这个值,进行相应的操作。
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用来解析你的代码。

一個普通的webpack設定檔如下:

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部分

在react 中,es6語法一般是要會一些的,針對react,關於es6一些基本的使用以及寫法,這裡列出來。

import和export

import引進一個東西

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;
    }
}

以上是React專案開發你需要知道哪些? react專案開發具體事項(附實例)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
C和JavaScript:連接解釋C和JavaScript:連接解釋Apr 23, 2025 am 12:07 AM

C 和JavaScript通過WebAssembly實現互操作性。 1)C 代碼編譯成WebAssembly模塊,引入到JavaScript環境中,增強計算能力。 2)在遊戲開發中,C 處理物理引擎和圖形渲染,JavaScript負責遊戲邏輯和用戶界面。

從網站到應用程序:JavaScript的不同應用從網站到應用程序:JavaScript的不同應用Apr 22, 2025 am 12:02 AM

JavaScript在網站、移動應用、桌面應用和服務器端編程中均有廣泛應用。 1)在網站開發中,JavaScript與HTML、CSS一起操作DOM,實現動態效果,並支持如jQuery、React等框架。 2)通過ReactNative和Ionic,JavaScript用於開發跨平台移動應用。 3)Electron框架使JavaScript能構建桌面應用。 4)Node.js讓JavaScript在服務器端運行,支持高並發請求。

Python vs. JavaScript:比較用例和應用程序Python vs. JavaScript:比較用例和應用程序Apr 21, 2025 am 12:01 AM

Python更適合數據科學和自動化,JavaScript更適合前端和全棧開發。 1.Python在數據科學和機器學習中表現出色,使用NumPy、Pandas等庫進行數據處理和建模。 2.Python在自動化和腳本編寫方面簡潔高效。 3.JavaScript在前端開發中不可或缺,用於構建動態網頁和單頁面應用。 4.JavaScript通過Node.js在後端開發中發揮作用,支持全棧開發。

C/C在JavaScript口譯員和編譯器中的作用C/C在JavaScript口譯員和編譯器中的作用Apr 20, 2025 am 12:01 AM

C和C 在JavaScript引擎中扮演了至关重要的角色,主要用于实现解释器和JIT编译器。1)C 用于解析JavaScript源码并生成抽象语法树。2)C 负责生成和执行字节码。3)C 实现JIT编译器,在运行时优化和编译热点代码,显著提高JavaScript的执行效率。

JavaScript在行動中:現實世界中的示例和項目JavaScript在行動中:現實世界中的示例和項目Apr 19, 2025 am 12:13 AM

JavaScript在現實世界中的應用包括前端和後端開發。 1)通過構建TODO列表應用展示前端應用,涉及DOM操作和事件處理。 2)通過Node.js和Express構建RESTfulAPI展示後端應用。

JavaScript和Web:核心功能和用例JavaScript和Web:核心功能和用例Apr 18, 2025 am 12:19 AM

JavaScript在Web開發中的主要用途包括客戶端交互、表單驗證和異步通信。 1)通過DOM操作實現動態內容更新和用戶交互;2)在用戶提交數據前進行客戶端驗證,提高用戶體驗;3)通過AJAX技術實現與服務器的無刷新通信。

了解JavaScript引擎:實施詳細信息了解JavaScript引擎:實施詳細信息Apr 17, 2025 am 12:05 AM

理解JavaScript引擎內部工作原理對開發者重要,因為它能幫助編寫更高效的代碼並理解性能瓶頸和優化策略。 1)引擎的工作流程包括解析、編譯和執行三個階段;2)執行過程中,引擎會進行動態優化,如內聯緩存和隱藏類;3)最佳實踐包括避免全局變量、優化循環、使用const和let,以及避免過度使用閉包。

Python vs. JavaScript:學習曲線和易用性Python vs. JavaScript:學習曲線和易用性Apr 16, 2025 am 12:12 AM

Python更適合初學者,學習曲線平緩,語法簡潔;JavaScript適合前端開發,學習曲線較陡,語法靈活。 1.Python語法直觀,適用於數據科學和後端開發。 2.JavaScript靈活,廣泛用於前端和服務器端編程。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版