Home  >  Article  >  Web Front-end  >  How to configure react development environment? React+webpack development environment configuration steps (results)

How to configure react development environment? React+webpack development environment configuration steps (results)

寻∝梦
寻∝梦Original
2018-09-11 11:12:112157browse

This article mainly talks about the final results of the development environment configuration steps of react webpack. Let’s read this article together

Configuration steps (1):How to configure the development environment for React? React webpack development environment configuration steps (with configuration examples)

Configuration steps (2): How to configure the development environment for react? React webpack development environment configuration steps (in-depth article)

Here we will first explain the reasons and practices of each step. Configuration step (4) will talk about how to quickly build webpack and share the entire project package to git.

Directory
4. React configuration
1. React component
2. React router module
3. React and Redux cooperation


In the previous article, we have explained how to configure the entire webpack environment. There will be an article later on how to quickly build webpack.

1. React component

First use node.js to install react and react-dom modules:

npm install react react-dom --save

In webpack.dll.config.js Add the react-dom third library

const vendors = [  
  'react',  "react-dom"];

to the vendors array inside. Type the following command in the Powershell window to package the third-party library into a dll.

webpack -p --config webpack.dll.config.js --progress --profile --colors

After the command is completed, manifest.json and vendor.xxxx.js will be updated. At this time, you need to manually refresh the vendor.xxxx.js file introduced in the html template.

Modify the content in app.js and add the rendering statement of reactdom:

require('./css/css');require('./less/less.less');require('./scss/scss.scss');var app=document.createElement("p");
app.innerHTML=&#39;<h1>Hello World!</h1>&#39;;document.body.insertBefore(app,document.body.childNodes[0]);

//The following is the react code

import React from &#39;react&#39;;
import ReactDOM from &#39;react-dom&#39;;class FirstComponent extends React.Component{
    render(){      return(
          <p>             this is React code from Components.          
          </p>
      );  
    }
}
var p=document.createElement("p");p.setAttribute("id","root");
document.body.insertBefore(p,document.body.childNodes[1]);
ReactDOM.render(<FirstComponent/>,document.getElementById(&#39;root&#39;));

Type npm start in powershell to start the server , type localhost:8080 on the browser to display the content of this web page.

2.React router module

First install the corresponding module: react-router-dom, command:

npm install react-router-dom --save

This module also needs to be added to Add the react-dom third library

const vendors = [  
  &#39;react&#39;,  "react-dom"];

to the vendors array in webpack.dll.config.js. Type the following command in the Powershell window to package the third-party library into the dll.

webpack -p --config webpack.dll.config.js --progress --profile --colors

After the command is completed, manifest.json and vendor.xxxx.js will be updated. At this time, you need to manually refresh the vendor.xxxx.js file introduced in the html template.

Modify the content in app.js:

import React from &#39;react&#39;;import ReactDOM from &#39;react-dom&#39;;import {NavLink,Route,BrowserRouter,HashRouter as Router, Swith,Redirect} from &#39;react-router-dom&#39;;import RouteConfig from &#39;../Config/Route.jsx&#39;;var p=document.createElement("p");
p.setAttribute("id","root");document.body.insertBefore(p,document.body.childNodes[1]);
ReactDOM.render(
    <Router>
        {RouteConfig}
    </Router>
    ,document.getElementById(&#39;root&#39;));

The current router has two versions, use react-router or react-router-dom. React-router-dom is used here. This module has several interfaces: NavLink, Route, BrowserRouter, HashRouter, Swith, Redirect, etc. I will not explain the function of each interface. RouteConfig is a routing configuration file, created by yourself.

Now we need to create several files,
1) Create a Config folder in the root directory, and create Route.jsx in the folder.
Contents of Route.jsx:

import React from &#39;react&#39;;
import ReactDOM from &#39;react-dom&#39;;
import {NavLink,Route,BrowserRouter as Router,HashRouter,Switch,Redirect}  from &#39;react-router-dom&#39;;

import MainComponent from &#39;../component/Main.jsx&#39;;//引进组件import Topic from &#39;../component/Topic.jsx&#39;;//引进组件const routes =[
    {
        path:&#39;/&#39;,
        exact:true,
        component: MainComponent
    },
    {
        path:&#39;/topic&#39;,
        exact:false,
        component:Topic
    },
];const RouteConfig = (
    <Switch>
    {
      routes.map((route,index)=>(
                  <Route
                   key ={index}
                   path={route.path}
                   exact={route.exact}
                   component={route.component}                
                  />
                ))
    }
    </Switch>
);
export default RouteConfig;

2) Create a component folder in the root directory and create two files under the folder:
Main.jsx:

import React from &#39;react&#39;;import ReactDOM from &#39;react-dom&#39;;import {NavLink as Link} from &#39;react-router-dom&#39;;class MainComponent extends React.Component{
    render(){      return(
          <p>
             <h1>mainText</h1>    

             <Link to="/topic">jumpe to Topic</Link>         
          </p>
      );  
    }
}

export default MainComponent;

Topic.jsx

import React from &#39;react&#39;;import ReactDOM from &#39;react-dom&#39;;import {NavLink as Link} from &#39;react-router-dom&#39;;class Topic extends React.Component{
    render(){      return(
          <p>
              <h1>topicText:</h1>         
              <Link to="/">jumpe to Main</Link>         
          </p>
      );  
    }
}

export default Topic;

After completion, type npm start in the powershell window, and then type localhost:8080 in the browser address bar. The following page will appear:
How to configure react development environment? React+webpack development environment configuration steps (results)

Click jump to Topic, it will jump to the topic page:
How to configure react development environment? React+webpack development environment configuration steps (results)

##In this way, webpack react router is simply configured.

3. React and Redux cooperate with

The Redux module can centrally manage the state of all react components. This technology is very commonly used.

Install the Redux module, command:

 npm install redux react-redux react-router-redux redux-thunk --save

After the module is installed, you need to modify the content of vendors in webpack.dll.config.js:

const vendors = [  &#39;react&#39;,  "react-dom",  "react-router-dom",  "redux",  "react-redux",  "react-router-redux",  "redux-thunk"];

In the Powershell window, type:

webpack -p --config webpack.dll.config.js --progress --profile --colors

The manifest.json and vendor.xxxxx.js files will be generated again under the build path, and the corresponding vendor.xxxxx.js files will be introduced into the index.html template file.

To use redux, you need to understand its basic principles first. I will briefly explain it here. You can learn more about it on Baidu.

Redux is mainly divided into three parts, store reducer action.
store is used to store the state that needs to be managed centrally in the component;
action is a series of methods that define a series of methods related to state changes (methods are also called action creators);
reducer is a method for initializing state and calling action Modify the state of the state and return the new state.
How these three are related to each other will be mentioned in the following steps.

store 一般会采用自动创建的方法。react组件可以通过函数直接上传给store,上传代码是直接写在组件里面,不需要添加一个组件就修改一次store的代码。
store 的中间件用来实现异步调用,这里用ReduxThunk。这个中间件的优缺点,暂时不涉及。
在src 目录下创建一个Config 文件夹,在Config 里面新建一个Store.jsx。
Store.jsx 的代码:

import {createStore,combineReducers,applyMiddleware} from &#39;redux&#39;;
import RootReducer from &#39;../Reducer/index.jsx&#39;;//引入reduceimport ReduxThunk from &#39;redux-thunk&#39;;//中间件var store = createStore(    //自动生成store的函数
    RootReducer, //reduce,修改state状态的函数集合
    applyMiddleware(ReduxThunk) //中间件);

export default store;

RootReducer是自己定义的reduce文件。createStore applyMiddleware 来自redux 模块。 ReduxThunk 来自于redux-thunk。
store 和 reducer 是通过createStore 关联起来的。

action
在src下面创建一个action文件夹,action文件夹下新建一个action.jsx文件。
action代码:

const actions = {

 changeText:function(num){
     console.log("调用actions");      switch(num){      case 1:      return {type:&#39;AlterMain&#39;,payload:"mainContainer had been changed"};      case 2:       return {type:&#39;AlterTopic&#39;,payload:"topicContainer had been changed"};       default:       return action;

   }
},

};
export default actions;

预先规划设定state格式为:
const defaultState = { //在reducer 里面定义state的初始的值
  mainText:”mainContainer”,
  topicText:”topicContainer”

};
action这里定义了一个修改state状态的函数。当reducer调用action时,action就会通过不同的情况返回不同的action值。

reducer:
在src文件夹下面创建一个Reducer文件夹,文件夹下面新建一个index.jsx文件。
reducer的代码:

import {combineReducers} from &#39;redux&#39;;import {routerReducer} from &#39;react-router-redux&#39;;const defaultState = {//设定state的默认值
   mainText:"mainContainer",
   topicText:"topicContainer"};const reducer = (state = defaultState, action) => {     
    switch (action.type) {//通过action的返回值来选择更新哪个state的状态
        case &#39;AlterMain&#39;:            return  Object.assign({},state,{ mainText:action.payload});        case &#39;AlterTopic&#39;:            return  Object.assign({},state,{ topicText:action.payload});        default:            return state;
    }
};const RootReducer = combineReducers({//可以定义多个reducer,然后通过combineReducers来合并
    routing:routerReducer,//redux和router处理函数
    app:reducer      //app 需要与组件里面上传的state一致});
export default RootReducer;

reducer 只看到 通过action返回值来修改state的状态并没有看到调用action。
在调试移动端显示的时候,发现object.assign 存在兼容问题,在网上查了下资料,需要额外添加下面这段代码:

if (typeof Object.assign != &#39;function&#39;) {    // Must be writable: true, enumerable: false, configurable: true
    Object.defineProperty(Object, "assign", {
      value: function assign(target, varArgs) { // .length of function is 2        &#39;use strict&#39;;        if (target == null) { // TypeError if undefined or null
          throw new TypeError(&#39;Cannot convert undefined or null to object&#39;);
        }        var to = Object(target);        for (var index = 1; index < arguments.length; index++) {          var nextSource = arguments[index];          if (nextSource != null) { // Skip over if undefined or null
            for (var nextKey in nextSource) {              // Avoid bugs when hasOwnProperty is shadowed
              if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
                to[nextKey] = nextSource[nextKey];
              }
            }
          }
        }        return to;
      },
      writable: true,
      configurable: true
    });
  }

组件的定义:
修改component文件夹下的Main.jsx(想看更多就到PHP中文网React参考手册栏目中学习)

import React from &#39;react&#39;;import ReactDOM from &#39;react-dom&#39;;import {NavLink as Link} from &#39;react-router-dom&#39;;import {connect} from &#39;react-redux&#39;;import P from &#39;prop-types&#39;;import actions from &#39;../src/action/action.jsx&#39;;//引入actions//mapstoreStateToProps 这里指定Main控件需要上传的stateconst mapStoreStateToProps = (state) =>(
    {
         mainText:state.app.mainText, //mainText是变量,值对应的state.app.mainText的存储空间,其中app与reducers里面定义的一致。

    }
);//mapDispatchToProps 这里上传处理state函数,即action里面定义的函数const mapDispatchToProps = (dispatch,ownProps)=> ({
   fn:{
       changeText:(num)=> dispatch(actions.changeText(num))
   }
});//这样state一致上传到store,需要取值用props取就okclass MainComponent extends React.Component{
    render(){      return(
          <p>
             <h1>mainText:{this.props.mainText}</h1>        
             <button onClick={()=>this.props.fn.changeText(1)}>修改mainText的值</button>

             <Link to="/topic">jumpe to Topic</Link>         
          </p>
      );  
    }
}//最后调用connect函数,把组件和store连接起来export default connect(mapStoreStateToProps,mapDispatchToProps)(MainComponent);

connect 函数能成功执行的前提是 组件是provider的子组件。所有需要修改app.js 。
app.js 代码:

import React from &#39;react&#39;;import ReactDOM from &#39;react-dom&#39;;import {NavLink,Route,BrowserRouter,HashRouter as Router, Swith,Redirect} from &#39;react-router-dom&#39;;import RouteConfig from &#39;../src/Config/Route.jsx&#39;;import {Provider} from &#39;react-redux&#39;;import store from &#39;../src/Config/Store.jsx&#39;;var p=document.createElement("p");
p.setAttribute("id","root");document.body.insertBefore(p,document.body.childNodes[0]);

ReactDOM.render(
    <Provider store={store}> //Provider 并指定store的文件
        <Router>
            {RouteConfig}
        </Router>
    </Provider>
    ,document.getElementById(&#39;root&#39;));

Topic.jsx的代码:

import React from &#39;react&#39;;import ReactDOM from &#39;react-dom&#39;;import {NavLink as Link} from &#39;react-router-dom&#39;;import {connect} from &#39;react-redux&#39;;import actions from &#39;../src/action/action.jsx&#39;;const mapStoreStateToProps = (state) =>(
    {         topicText:state.app.topicText,

    }
)const mapDispatchToProps = (dispatch,ownProps)=> ({   fn:{       changeText:(num)=> dispatch(actions.changeText(num))
   }
});class Topic extends React.Component{
    render(){      return(
          <p>
              <h1>topicText:{this.props.topicText}</h1>
              <button onClick={()=>this.props.fn.changeText(2)}>修改topicText的值</button>       
              <Link to="/">jumpe to Main</Link>         
          </p>
      );  
    }
}export default connect(mapStoreStateToProps,mapDispatchToProps)(Topic);

这样整个redux就搭建好了。

provider 指定 store文件,它下面的组件可以通过connect 把组件和store关联。
store:通过createStore 把 store和reducer 关联
reducer: 定义state的默认值,并定义state 和action的对应关系。combineReducers 合并reducer,指定reducer的接口,如果用到router时,要注意定义route的处理函数。
action:只是单独定义一些修改state状态的操作。
组件:通过connect 把需要集中管理的state即state对应的action 上传到store,并绑定组件。state的值被修改,组件的view就会做相应的改变

这里没有涉及到redux的异步通信。
流程可以简化理解为:
组件->action->dispath(action)->store->reducer ->store(修改state)->组件(view)

网页的整体效果如下:
用http://localhost:8080 就能看到下面的界面:
How to configure react development environment? React+webpack development environment configuration steps (results)

点击修改mainText的值 的按钮,mainText就会被更改如下:
How to configure react development environment? React+webpack development environment configuration steps (results)点击jumpe to Topic
How to configure react development environment? React+webpack development environment configuration steps (results)

点击 修改topicText的值 的按钮,topicText就会被更改如下:
How to configure react development environment? React+webpack development environment configuration steps (results)

本篇文章到这就结束了(想看更多就到PHP中文网React使用手册栏目中学习),有问题的可以在下方留言提问。

The above is the detailed content of How to configure react development environment? React+webpack development environment configuration steps (results). 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