这个项目标识:构建一套适合 React、ES6 开发的脚手架

项目地址为:https://github.com/ZengTianShengZ/react-lesson

运行的是第一课,基本上可以当作是一个小型的项目,毕竟路由还有组件目录挺全的,不过,没有深入,记一下

//lesson-1/index.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no, minimal-ui">
<meta name="format-detection" content="telephone=no">
<title>react - lession</title>
<link href="/build/static/app.css" rel="stylesheet">
</head>
<body> <script type="text/javascript" src="/build/static/app.js"></script>
</body>
</html>
//lesson-1/src/App.jsx
import ReactDOM, {render} from 'react-dom';
import React, {Component, PropTypes} from 'react';
import {Router,Route,hashHistory} from 'react-router';
import Main from './Component/Main.jsx'
//import Page1 from './Component/Page1.jsx'
import './Style/comm.scss' const Page1 = (location, cb) => {
require.ensure([], require => {
cb(null, require('./Component/Page1').default)
},'Page1')
} render(
<Router history={hashHistory}>
<Route path='/' component={Main} />
<Route path='/page1' getComponent={Page1} />
</Router>,
document.body.appendChild(document.createElement('div'))
);

//lesson-1/src/Component/Main.jsx
import React, {Component, PropTypes} from 'react';
import {Link} from 'react-router'; class Main extends Component {
constructor() {
super();
}
render(){
return(
<div>
<h1>lesson 1 </h1>
<p>webpack 构建一套适合 React、ES6 开发的脚手架 </p>
<Link to="/page1" activeStyle={{color: 'blue'}}>page1</Link>
</div>
)
}
}
export default Main;

//lesson-1/src/Component/page1.jsx
import React, {Component, PropTypes} from 'react'; class Page1 extends Component {
constructor() {
super();
}
render(){
return(
<div>
<h1>lesson 1 </h1>
<p>page1</p>
</div>
)
}
}
export default Page1;

项目中的第二个例子就是老生常谈了

太冗杂了,我都不愿意去看,一般都会抽分reducer,action,store

//lesson-2/src/App.jsx
import React,{Component,PropTypes} from 'react';
import ReactDOM, {render} from 'react-dom';
import {Provider,connect} from 'react-redux';
import {createStore, combineReducers, applyMiddleware} from 'redux';
import Index from './Component/Main.jsx';
import './Style/comm.scss' // reducer
const reducer = (state = {count: 0}, action) => {
switch (action.type){
case 'INCREASE': return {count: state.count + 1};
case 'DECREASE': return {count: state.count - 1};
default: return state;
}
}
const store = createStore(reducer);
//监听state变化
store.subscribe(() => {
//console.log(store.getState())
});
render(
<Provider store={store}>
<Index></Index>
</Provider>,
document.body.appendChild(document.createElement('div'))
);
//lesson-2/src/Component/Main.jsx
import React, {Component, PropTypes} from 'react';
import {connect} from 'react-redux'; /**
* 定义一个 Main组件
*/
class Main extends Component{
constructor(){
super();
this.pClick =() =>{
console.log('sssssssss');
};
this.state = {
num:0,
age:666
}
}
render(){
// 拿到 this.props 参数
const {count, increase, decrease} = this.props;
return(
<div>
<p className="lesson-2">React lesson-2</p>
<p>
---------------------------------
</p>
<div className="count">
<div>计数:{this.props.count}次</div>
<span className="btn" onClick={increase}>+</span>
<span className="btn" onClick={decrease}>-</span>
</div>
</div>
)
}
}
/**
* 用来给 组件传递数据
* @param state
*/
const mapStateToProps = (state) => {
return {
count: state.count
}
};
/**
*用来组件给 容器组件派发数据
* @param dispatch 派发 Action
* @param ownProps 组件自身的 props参数
*/
const mapDispatchToProps = (dispatch, ownProps) => {
return {
increase: (...args) => dispatch(actions.increase(...args)),
decrease: (...args) => dispatch(actions.decrease(...args))
}
};
/**
* actions
*/
const actions ={
increase:() => {
return {type: 'INCREASE'}
},
decrease: () => {
return {type: 'DECREASE'}
}
};
/**
* 连接 UI组件 和 容器组件
* @param mapStateToProps 输入逻辑
* @param mapDispatchToProps 输出逻辑
*/
const Comp = connect(mapStateToProps, mapDispatchToProps)(Main);
/**
* 输出一个容器组件
*/
export default Comp;

哎,第三节也是简单的项目

不过 服务是nodejs起的

//lesson-3/server.js
var express = require('express');
var app = express();
var dataJson = require('./dataJson.json'); app.use(express.static('build'))
/**
* get: 请求
* url: http://127.0.0.1:8088/getData
*/
app.get('/getData',function(req,res){
var resData = {
err:0,
data:dataJson
}
res.end(JSON.stringify(resData));
})
app.get('/', function (req, res) {
res.sendFile(__dirname + '/build/index.html')
})
var server = app.listen(8088, function () {
console.log('正常打开8088端口');
})
//lesson-3/server_hot.js
var webpack = require('webpack');
var express = require('express');
var config = require('./webpack.config.hot');
var dataJson = require('./dataJson.json');
var app = express();
var compiler = webpack(config); app.use(require('webpack-dev-middleware')(compiler, {
publicPath: config.output.publicPath,
hot: true,
historyApiFallback: true,
inline: true,
progress: true,
stats: {
colors: true,
}
})); app.use(require('webpack-hot-middleware')(compiler)); /**
* get: 请求
* url: http://127.0.0.1:8088/getData
*/
app.get('/getData',function(req,res){
var resData = {
err:0,
data:dataJson
}
res.end(JSON.stringify(resData));
})
/**
* 将其他路由,全部返回index.html
*/
app.get('/*', function(req, res) {
res.sendFile(__dirname + '/index.html')
});
app.listen(8088, function() {
console.log('正常打开8088端口')
});
//lesson-3/src/App.jsx
import React,{Component,PropTypes} from 'react';
import {Provider,connect} from 'react-redux';
import ReactDOM, {render} from 'react-dom';
import store from './Redux/store'
import router from './Router/router' import './Style/comm.scss' store.subscribe(() => { }); render(
<Provider store={store}>
{router}
</Provider>,
document.getElementById('root')
);



//lesson-3/src/Router/router.jsx
// 有用到懒加载
import React, {Component, PropTypes} from 'react';
import { Router, Route, Redirect, IndexRoute, browserHistory, hashHistory } from 'react-router';
import Index from '../Component/Index.jsx';
/*=================
router.jsx 组件
专门用来管理路由的
==================*/
/**
Page2 组件按需加载
*/
const page2 = (location, cb) => {
require.ensure([], require => {
cb(null, require('../Component/Page2').default)
},'page2')
} const RouteConfig =(
<Router history={hashHistory}>
<Route path='/' component={Index}/>
<Route path='/page2' getComponent={page2}/>
</Router>
)
export default RouteConfig
//lesson-3/src/Component/Loading.jsx
import React, {Component, PropTypes} from 'react';
import {connect} from 'react-redux';
import template from './common/template'
/*=================
BottonView.jsx 子组件
==================*/
class LoadingView extends Component{
constructor(){
super();
}
render(){
let{fData} = this.props;
let loadingStyle;
if(fData.loading){
loadingStyle = {
opacity: 1
}
}else{
loadingStyle = {
opacity: 0
}
}
return(
<div id='LoadingView' style={loadingStyle}>
</div>
)
}
shouldComponentUpdate(nextProps, nextState){
return true;
}
}
export default template({
id:'',
url:'',
subscribeData:['fData'],
component:LoadingView
})
//lesson-3/src/Redux/action.jsx
import fetch from 'isomorphic-fetch'
/*=================
action.jsx
派发 action
==================*/
export const increase = data => {
return {type: 'INCREASE',data:data}
}
export const decrease = data => {
return {type: 'DECREASE',data:data}
} const dispathData = (path,json) => {
return {
type: 'DISPATHDATA',
path:path,
json:json
}
}
export const fetchData = (url ,data) => {
return dispatch =>{
// 先派发一个 LOADING action
dispatch({type:'LOADING'});
fetch(url,{
mode: 'cors',
"Content-Type": "application/json"
})
.then(function(response) {
if (response.status >= 400) {
throw new Error("Bad response from server");
}
return response.json();
})
.then(function(data){
// 这里延时只是为了演示效果,实际开发中需要把延时去掉
setTimeout(function(){
// 数据请求成功 再派发一个 getData action
return dispatch(dispathData('getData',data));
},3000);
})
.catch(function(error) {
console.log('Request failed', error)
});
}
}
//lesson-3/src/Redux/reducer.jsx
import Immutable from 'immutable'
/*=================
reducer.jsx
接收Action 并作出处理
==================*/
export const increaseData = (state =Immutable.fromJS({ count: 0}), action={}) => {
switch (action.type){
case 'INCREASE':
return Immutable.Map({count:action.data+1});
default: return state;
}
};
export const decreaseData = (state = Immutable.fromJS({ count: 8}), action={}) => {
switch (action.type){
case 'DECREASE':
return Immutable.Map({count:action.data-1});
default: return state;
}
};
export const fData = (state = {data:{},loading:false}, action={}) => {
switch (action.type){
case 'LOADING':
return {
data:{},
loading:true
};
case 'DISPATHDATA':
return {
data: action.json,
loading:false
};
default: return state;
}
}
//lesson-3/src/Redux/store.jsx
import {createStore, combineReducers, applyMiddleware} from 'redux';
import thunk from 'redux-thunk';
import * as reducer from './reducer'
/*=================
store.jsx
中央数据处理器
==================*/
var store = createStore(
combineReducers(reducer),
applyMiddleware(thunk)
);
export default store;

【心有猛虎】react-lesson的更多相关文章

  1. [React] React Fundamentals: Mixins

    Mixins will allow you to apply behaviors to multiple React components. Components are the best way t ...

  2. [React] React Fundamentals: Component Lifecycle - Updating

    The React component lifecycle will allow you to update your components at runtime. This lesson will ...

  3. [React] React Fundamentals: Component Lifecycle - Mounting Basics

    React components have a lifecycle, and you are able to access specific phases of that lifecycle. Thi ...

  4. [React] React Fundamentals: transferPropsTo

    the transferPropsTo method lets you easily push properties into your components to easily customize ...

  5. [React] React Fundamentals: Accessing Child Properties

    When you're building your React components, you'll probably want to access child properties of the m ...

  6. [React] React Fundamentals: Using Refs to Access Components

    When you are using React components you need to be able to access specific references to individual ...

  7. [React] React Fundamentals: Owner Ownee Relationship

    The owner-ownee relationship is used to designate a parent-child relationship with React components ...

  8. [React] React Fundamentals: State Basics

    State is used for properties on a component that will change, versus static properties that are pass ...

  9. [React] React Fundamentals: First Component

    <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8&quo ...

  10. [React] React Fundamentals: with-addons - ReactLink

    It can be tedious to type out all the boilerplate needed to get the DOM and states in React to synch ...

随机推荐

  1. Python中的sort()

    Python中的sort()方法用于数组排序,本文以实例形式对此加以详细说明: 一.基本形式列表有自己的sort方法,其对列表进行原址排序,既然是原址排序,那显然元组不可能拥有这种方法,因为元组是不可 ...

  2. 第三章 Odoo 12 开发之创建第一个 Odoo 应用

    Odoo 开发通常都需要创建自己的插件模块.本文中我们将通过创建第一个应用来一步步学习如何在 Odoo 中开启和安装这个插件.我们将从基础的开发流学起,即创建和安装新插件,然后在开发迭代中更新代码来进 ...

  3. SQL Server作业的备份

    作业备份,不是备份数据库,是备份作业.我的方法是把作业导出成文件备份起来,因为当你服务器维护的多了的时候很多你的作业 就很成问题,很麻烦.最好能够作业实现同步,这个也是第一步,保存成文件,之后个人设想 ...

  4. 深入浅出 Java Concurrency (10): 锁机制 part 5 闭锁 (CountDownLatch)[转]

    此小节介绍几个与锁有关的有用工具. 闭锁(Latch) 闭锁(Latch):一种同步方法,可以延迟线程的进度直到线程到达某个终点状态.通俗的讲就是,一个闭锁相当于一扇大门,在大门打开之前所有线程都被阻 ...

  5. JS防抖动

    这道题目经常与事件触发器同时存在,为了考察面试者在一些具体业务流程上(信息流,搜索框输入查询)等,能否综合的考虑实现思路. 题目:在某些信息列表中一般采用瀑布流,滚动一屏时加载相应的数据,请思考如何避 ...

  6. ArrayList基础知识

    ArrayList简介 ArrayList 的底层是数组队列,相当于动态数组.与 Java 中的数组相比,它的容量能动态增长.在添加大量元素前,应用程序可以使用ensureCapacity操作来增加 ...

  7. Linq之Sum用法新体会

    1.简单应用,求数组的和,示例: , , , , , , , , , }; double numSum = numbers.Sum(); Console.WriteLine("The sum ...

  8. SQL 查询--日期条件(今日、昨日、本周、本月。。。) (转)

    主要用到sql 函数 DATEDIFF(datepart,startdate,enddate) sql 语句,设 有 数据库表 tableA(日期字段ddate) ——查询 今日 select * f ...

  9. pixhawk 常见问题 持续更新

    红灯蓝灯闪,初始化中,请稍等 黄灯双闪,错误,系统拒绝解锁 黄灯闪,遥控器关闭 黄灯快速闪且滴滴响,电池保护激活 蓝灯... 未见过.... 绿灯闪: 已加锁,GPS锁定已获得. 准备解锁. 从加锁状 ...

  10. servlet接收request请求的json数据

    此次使用的是alibaba的fastjson:jar包为fastjson-1.2.7.jar 参考:https://www.qingtingip.com/h_229797.html 思路:由于此次接收 ...