標籤:
1、安裝node 相關包
npm install --save react react-dom superagent
2、安裝gulp相關包
npm install --save gulp-browserify gulp reactify gulp-connect
3、編寫gulpfile.js 構建React檔案
var gulp = require(‘gulp‘), browserify = require(‘gulp-browserify‘), reactify = require(‘reactify‘), connect = require(‘gulp-connect‘);gulp.task(‘build‘, function() { gulp.src(‘index.js‘). pipe(browserify({ transform: [‘reactify‘] })) .pipe(gulp.dest(‘build.js‘))})gulp.task(‘connect‘, function() { connect.server({ port: 3000, livereload: true })})gulp.task(‘html‘, function() { gulp.src(‘*.html‘) .pipe(connect.reload())})gulp.task(‘js‘,[‘build‘], function() { gulp.src(‘*.js‘) .pipe(connect.reload())})gulp.task(‘watch‘, function() { gulp.watch(‘*.html‘, [‘html‘]) gulp.watch(‘*.js‘, [‘js‘])})gulp.task(‘default‘, [‘build‘, ‘watch‘, ‘connect‘])
4、編寫request請求
1、新增常量檔案 constants.js 用來存放 request 請求中 Basic 認證的使用者名稱 密碼
module.exports={ uname:‘123‘, pwd:‘123‘}
2、新增調用 API 檔案 api.js
var request = require(‘superagent‘);var constants = require(‘./constants.js‘);module.exports = { Get: function(callback) { request .get(‘http://localhost:53691/api/value‘) .auth(constants.uname, constants.pwd) .end(function(err, res) { if(err){ alert(err); } callback(res.body); }); }}
5、新增index.js
var React=require(‘react‘), ReactDOM=require(‘react-dom‘), API=require(‘./Api.js‘);var ItemList=React.createClass({ getInitialState:function(){ return { Users:[] } }, componentWillMount:function(){ var users=API.Get(function(users){ this.setState({ Users: users }) }.bind(this)); }, render:function(){ var users=this.state.Users; if(Array.isArray(users)==false)throw new Error(‘users is not array‘) var lists=users.map(function(item){ return <li key={item.ID}>{item.ID}:{item.Name}</li> }) return ( <ul> {lists} </ul> ) }});ReactDOM.render(<ItemList />,document.getElementById(‘app‘))
6、新增index.html
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Document</title></head><body> <h1>SuperAgent!</h1> <div id="app"></div> <script src="build.js/index.js"></script></body></html>
WebApi源碼
React 中 調用 Asp.net WebApi