reactjs 启动fullstack 怎么启动

问题对人有帮助,内容完整,我也想知道答案
问题没有实际价值,缺少关键内容,没有改进余地
vuejs angular reactjs 选哪个
场景:想来替代 php模板引擎实现 ios,android,web前端 调用同一个接口统一后端
答案对人有帮助,有参考价值
答案没帮助,是错误的答案,答非所问
跟你用上述几个框架一点关系都没有。结论:选一个自己熟悉的
答案对人有帮助,有参考价值
答案没帮助,是错误的答案,答非所问
用vue快速满足需求,然后想办法用react来积累你的组件,我保证你以后会非常感谢现在的自己!
分享到微博?
Hi,欢迎来到 SegmentFault 技术社区!⊙▽⊙ 在这里,你可以提出编程相关的疑惑,关注感兴趣的问题,对认可的回答投赞同票;大家会帮你解决编程的问题,和你探讨技术更新,为你的回答投上赞同票。
明天提醒我
关闭理由:
删除理由:
忽略理由:
推广(招聘、广告、SEO 等)方面的内容
与已有问题重复(请编辑该提问指向已有相同问题)
答非所问,不符合答题要求
宜作评论而非答案
带有人身攻击、辱骂、仇恨等违反条款的内容
无法获得确切结果的问题
非开发直接相关的问题
非技术提问的讨论型问题
其他原因(请补充说明)
我要该,理由是:
扫扫下载 App
SegmentFault
一起探索更多未知reactjs - Bootstrap collapse with react js - Stack Overflow
to customize your list.
Announcing Stack Overflow Documentation
We started with Q&A. Technical documentation is next, and we need your help.
Whether you're a beginner or an experienced developer, you can contribute.
Hi I'm trying to use bootstrap collapse inside a react view and it's not working. It's very simple but I don't understand what's going on.
return (&div&
&button className="btn" type="button" data-toggle="collapse" data-target="#collapseExample" aria-expanded="true" aria-controls="collapseExample"&
ButtonClickthis!
&div className="collapse" id="collapseExample"&
&div className="well"&
...blablablacontent
10.2k42143
2,24431125
Bootstrap will not work out of the box for react components, since it parses the DOM on load and attaches event listeners etc. You can try something like
or manually triggering inside the componentDidMount lifecycle.
I experienced this before. All you need to do is manually trigger events inside componentDidMount. You might also want to re-triggering the events in the callback of the setState.
Your Answer
Sign up or
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Post as a guest
By posting your answer, you agree to the
Not the answer you're looking for?
Browse other questions tagged
Stack Overflow works best with JavaScript enabledjavascript - Reactjs - Rerender on browser resize - Stack Overflow
to customize your list.
Announcing Stack Overflow Documentation
We started with Q&A. Technical documentation is next, and we need your help.
Whether you're a beginner or an experienced developer, you can contribute.
How can I get React to re-render the view when the browser window is resized?
Background
I have some blocks that I want to layout individually on the page, however I also want them to update when the browser window changes. The very end result will be something like
pinterest layout, but written using React not just jquery. I'm still a way off.
Here's my app:
var MyApp = React.createClass({
//does the http get from the server
loadBlocksFromServer: function() {
url: this.props.url,
dataType: 'json',
mimeType: 'textPlain',
success: function(data) {
this.setState({data: data.events});
}.bind(this)
getInitialState: function() {
return {data: []};
componentWillMount: function() {
this.loadBlocksFromServer();
render: function() {
&Blocks data={this.state.data}/&
React.renderComponent(
&MyApp url="url_here"/&,
document.getElementById('view')
Then I have the Block component (equivalent to a Pin in the above Pinterest example):
var Block = React.createClass({
render: function() {
&div class="dp-block" style={{left: this.props.top, top: this.props.left}}&
&h2&{this.props.title}&/h2&
&p&{this.props.children}&/p&
and the list/collection of Blocks:
var Blocks = React.createClass({
render: function() {
//I've temporarily got code that assigns a random position
//See inside the function below...
var blockNodes = this.props.data.map(function (block) {
//temporary random position
var topOffset = Math.random() * $(window).width() + 'px';
var leftOffset = Math.random() * $(window).height() + 'px';
return &Block order={block.id} title={block.summary} left={leftOffset} top={topOffset}&{block.description}&/Block&;
&div&{blockNodes}&/div&
Should I add jquery's window resize, if so where?
$( window ).resize(function() {
// re-render the component
Is there a more "React" way of doing this?
You can listen in componentDidMount, something like this component which just displays the window dimensions (like &span&1024 x 768&/span&):
var WindowDimensions = React.createClass({
render: function() {
return &span&{this.state.width} x {this.state.height}&/span&;
updateDimensions: function() {
this.setState({width: $(window).width(), height: $(window).height()});
componentWillMount: function() {
this.updateDimensions();
componentDidMount: function() {
window.addEventListener("resize", this.updateDimensions);
componentWillUnmount: function() {
window.removeEventListener("resize", this.updateDimensions);
(Note that addEventListener doesn't work in old versions of IE; you might prefer to use jQuery's on/off instead for cross-browser compatibility.)
58.6k21159198
@BenAlpert is right, +1, I just want to provide a modified version of his solution, without jQuery, based on .
var WindowDimensions = React.createClass({
render: function() {
return &span&{this.state.width} x {this.state.height}&/span&;
updateDimensions: function() {
var w = window,
d = document,
documentElement = d.documentElement,
body = d.getElementsByTagName('body')[0],
width = w.innerWidth || documentElement.clientWidth || body.clientWidth,
height = w.innerHeight|| documentElement.clientHeight|| body.clientH
this.setState({width: width, height: height});
// if you are using ES2015 I'm pretty sure you can do this: this.setState({width, height});
componentWillMount: function() {
this.updateDimensions();
componentDidMount: function() {
window.addEventListener("resize", this.updateDimensions);
componentWillUnmount: function() {
window.removeEventListener("resize", this.updateDimensions);
15.7k1979130
I will try to give a generic answer, that targets this specific problem but a more general problem also.
If you don't care about side effects libs, you can simply use something like
If you use Flux, you could create a store that contain the window properties so that you keep a pure render function without having to query the window object everytime.
In other cases where you want to build a responsive website but you prefer React inline styles to media queries, or want the HTML/JS behavior to change according to window width, keep reading:
What is React context and why I talk about it
an is not in the public API and permits to pass properties to a whole hierarchy of components.
React context is particularly useful to pass to your whole app things that never changes (it is used by many Flux frameworks through a mixin). You can use it to store app business invariants (like the connected userId, so that it's available everywhere).
But it can also be used to store things that can change. The problem is that when the context changes, all the components that use it should be re-rendered and it is not easy to do so, the best solution is often to unmount/remount the whole app with the new context. Remember .
So as you understand, context is practical, but there's a performance impact when it changes, so it should rather not change too often.
What to put in context
Invariants: like the connected userId, sessionToken, whatever...
Things that don't change often
Here are things that don't change often:
The current user language:
It does not change very oftenly, and when it does, as the whole app is translated we have to re-render everything: a very nice usecase of hot langage change
The window properties
Width and height to not change often but when we do our layout and behavior may have to adapt. For the layout sometimes it's easy to customize with CSS mediaqueries, but sometimes it's not and requires a different HTML structure. For the behavior you have to handle this with Javascript.
You don't want to re-render everything on every resize event, so you have to debounce the resize events.
What I understand of your problem is that you want to know how many items to display according to the screen width. So you have first to define , and enumerate the number of different layout types you can have.
For example:
Layout "1col", for width &= 600
Layout "2col", for 600 & width & 1000
Layout "3col", for 1000 &= width
On resize events (debounced), you can easily get the current layout type by querying the window object.
Then you can compare the layout type with the former layout type, and if it has changed, re-render the app with a new context: this permits to avoid re-rendering the app at all when the user has trigger resize events but actually the layout type has not changed, so you only re-render when required.
Once you have that, you can simply use the layout type inside your app (accessible through the context) so that you can customize the HTML, behavior, CSS classes... You know your layout type inside the React render function so this means you can safely write responsive websites by using inline styles, and don't need mediaqueries at all.
If you use Flux, you can use a store instead of React context, but if your app has a lot of responsive components maybe it's simpler to use context?
27.7k21139237
A very simple solution:
componentDidMount() {
window.addEventListener('resize', () =& this.forceUpdate())
It's a simple and short example of using es6 without jQuery.
class CreateContact extends Component{
constructor(props) {
super(props);
this.state = {
windowHeight: window.innerHeight,
windowWidth: window.innerWidth
handleResize(e) {
this.setState({
windowHeight: window.innerHeight,
windowWidth: window.innerWidth
componentDidMount() {
window.addEventListener('resize', ::this.handleResize)
componentWillUnmount() {
window.removeEventListener('resize', ::this.handleResize)
render() {
{this.state.windowWidth} x {this.state.windowHeight}
Not sure if this is the best approach, but what worked for me was first creating a Store, I called it WindowStore:
import {assign, events} from '../../libs';
import Dispatcher from '../dispatcher';
import Constants from '../constants';
let CHANGE_EVENT = 'change';
let defaults = () =& {
name: 'window',
width: undefined,
height: undefined,
let save = function(object, key, value) {
// Save within storage
if(object) {
object[key] =
// Persist to local storage
sessionStorage[storage.name] = JSON.stringify(storage);
let Store = assign({}, events.EventEmitter.prototype, {
addChangeListener: function(callback) {
this.on(CHANGE_EVENT, callback);
window.addEventListener('resize', () =& {
this.updateDimensions();
this.emitChange();
emitChange: function() {
this.emit(CHANGE_EVENT);
get: function(keys) {
let value =
for(let key in keys) {
value = value[keys[key]];
initialize: function() {
// Set defaults
storage = defaults();
this.updateDimensions();
removeChangeListener: function(callback) {
this.removeListener(CHANGE_EVENT, callback);
window.removeEventListener('resize', () =& {
this.updateDimensions();
this.emitChange();
updateDimensions: function() {
storage.width =
window.innerWidth ||
document.documentElement.clientWidth ||
document.body.clientW
storage.height =
window.innerHeight ||
document.documentElement.clientHeight ||
document.body.clientH
export default S
Then I used that store in my components, kinda like this:
import WindowStore from '../stores/window';
let getState = () =& {
windowWidth: WindowStore.get(['width']),
windowBps: WindowStore.get(['bps'])
export default React.createClass(assign({}, base, {
getInitialState: function() {
WindowStore.initialize();
return getState();
componentDidMount: function() {
WindowStore.addChangeListener(this._onChange);
componentWillUnmount: function() {
WindowStore.removeChangeListener(this._onChange);
render: function() {
if(this.state.windowWidth & this.state.windowBps[2] - 1) {
// do something
_onChange: function() {
this.setState(getState());
FYI, these files were partially trimmed.
I use @senornestor 's solution, but to be entirely correct you have to remove the event listener as well:
componentDidMount() {
window.addEventListener('resize', this.handleResize);
componentWillUnmount(){
window.removeEventListener('resize', this.handleResize);
handleResize = () =& {
this.forceUpdate();
Otherwise you 'll get the warning:
Warning: forceUpdate(...): Can only update a mounted or mounting
component. This usually means you called forceUpdate() on an unmounted
component. This is a no-op. Please check the code for the XXX
component.
I would skip all of the above answers and start using the react-dimensions Higher Order Component.
Just add a simple import and a function call, and you can access this.props.containerWidth and this.props.containerHeight in your component.
// Example using ES6 syntax
import React from 'react'
import Dimensions from 'react-dimensions'
class MyComponent ponent {
render() (
containerWidth={this.props.containerWidth}
containerHeight={this.props.containerHeight}
export default Dimensions()(MyComponent) // Enhanced component
1,01821328
Your Answer
Sign up or
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Post as a guest
By posting your answer, you agree to the
Not the answer you're looking for?
Browse other questions tagged
Stack Overflow works best with JavaScript enabledThe Ultimate Full-Stack React.js Tutorial
(window.slotbydup=window.slotbydup || []).push({
id: '2611110',
container: s,
size: '240,200',
display: 'inlay-fix'
您当前位置: &
[ 所属分类
| 时间 2015 |
作者 红领巾 ]
In this tutorial we are going to build a character voting app (inspired by Facemash and Hot or Not ) for EVE Online - a massively multiplayer online game. Be sure to play this awesome soundtrack below to get yourself in the mood for this epicly long tutorial.
While listening to this soundtrack, imagine yourself mining asteroid belts in deep space while keeping a lookout for pirates on the radar, researching propulsion system blueprints at the station's facility, manufacturing spaceship components for capital ships, placing buy & sell orders on the entirely player-driven market where supply and demand govern the game economics, hauling trade goods from a remote solar system in a massive freighter, flying blazingly fast interceptors with a microwarpdrive or powerful battleships armored to the teeth, optimizing extraction efficiency of rare minerals from planets, or fighting large-scale battles with thousands of players from multiple alliances. That's EVE Online .
Each player in EVE Online has a 3D avatar representing their character. This app is designed for ranking those avatars. Anyway, your goal here is to learn about Node.js and React, not EVE Online. But I will say this: "Having an interesting tutorial project is just as important, if not more so, than the main subject of the tutorial". The only reason I built the original New Eden Faces app is to learn
Backbone.js and the only reason I built the TV Show Tracker app is so that I could learn
AngularJS. To me, either one of these projects is far more interesting than a simple todo app that everyone seems to be using these days.
One thing that I have learned — between screencasts, books and training videos, nothing is more effective than building a small project that you are passionate about to learn a new technology.
Source Code
In the same spirit as my previous tutorials (TV Show Tracker and Instagram Clone ) this is a full-stack
tutorial where we build a complete app from the ground up.
This is a remake of the original
New Eden Faces (2013) project, which was my first ever single-page application written in Backbone.js. It has been running in production on
OpenShift with Node.js 0.8.x for over 2 years now.
I usually try to make as few assumptions as possible about a particular topic, which is why my tutorials are so lengthy, but having said that, you need to have at least some prior experience with client-side JavaScript frameworks and Node.js to get the most out of this tutorial.
Before proceeding, you will need to download and install the following tools:
Node.js (or io.js )
Step 1. New Express Project
Create a new directory
newedenfaces
. Inside, create 2 empty files package.json and server.js using your favorite text editor or using the command line:
Open package.json and paste the following:
"name": "newedenfaces",
"description": "Character voting app for EVE Online",
"version": "1.0.0",
"repository": {
"type": "git",
"url": "/sahat/newedenfaces-react"
"main": "server.js",
"scripts": {
"start": "babel-node server.js",
"watch": "nodemon --exec babel-node -- server.js"
"dependencies": {
"alt": "^0.17.1",
"async": "^1.4.0",
"babel": "^5.6.23",
"body-parser": "^1.13.2",
"colors": "^1.1.2",
"compression": "^1.5.1",
"express": "^4.13.1",
"mongoose": "^4.0.7",
"morgan": "^1.6.1",
"react": "^0.13.3",
"react-router": "^0.13.3",
"request": "^2.58.0",
"serve-favicon": "^2.3.0",
"socket.io": "^1.3.6",
"swig": "^1.4.2",
"underscore": "^1.8.3",
"xml2js": "^0.4.9"
"devDependencies": {
"babelify": "^6.1.3",
"bower": "^1.4.1",
"browserify": "^11.0.0",
"gulp": "^3.9.0",
"gulp-autoprefixer": "^2.3.1",
"gulp-concat": "^2.6.0",
"gulp-cssmin": "^0.1.7",
"gulp-if": "^1.2.5",
"gulp-less": "^3.0.3",
"gulp-plumber": "^1.0.1",
"gulp-streamify": "0.0.5",
"gulp-uglify": "^1.2.0",
"gulp-util": "^3.0.6",
"vinyl-source-stream": "^1.1.0",
"watchify": "^3.3.0"
"license": "MIT"
These are all the packages that we will be using in this project. I will briefly go over each package.
Package Name
Description
Flux library for React.
For managing asynchronous flow.
ES6 compiler.
body-parser
For parsing POST request data.
Pretty console output messages.
compression
Gzip compression.
Web framework for Node.js.
MongoDB ODM with validation and schema support.
HTTP request logger.
react-router
Routing library for React.
For making HTTP requests to EVE Online API.
serve-favicon
For serving favicon.png icon.
To display how many users are online in real-time.
To render the initial HTML template.
underscore
Helper JavaScript utilities.
For parsing XML response from EVE Online API.
Run npm install in the Terminal to install the packages that we specified in the package.json .
If you are using
cmder console emulator. It is the closest thing to Mac OS X/ Terminal experience.
Open server.js and paste the following code. It's a very minimal Express application, just enough to get us started.
var express = require('express');
var path = require('path');
var logger = require('morgan');
var bodyParser = require('body-parser');
var app = express();
app.set('port', process.env.PORT || 3000);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
app.listen(app.get('port'), function() {
console.log('Express server listening on port ' + app.get('port'));
Although we will be building the React app in ES6, I have decided to use ES5 here because this back-end code is mostly unchanged from when I first built the original
New Eden Faces project. Additionally, if you are using ES6 for the first time, then at least the Express app will still be familiar to you.
Next, create a new directory
. This is where we are going to place images, fonts , as well as compiled CSS and JavaScript files.
Run npm start in the Terminal to make sure our Express app is working without any issues.
While you could technically use
node server.js to start the app right now, as soon as we start writing the React app using ECMAScript 6 and pre-rendering it on the server, we will need the Babel compiler.
You should see the Express server listening on port 3000 message in the Terminal.
Step 2. Build System
If you have been around the web community at all, then you may have heard about Browserify and Webpack tools. If not, then consider the chaos that would arise from having to manually include so many &script& tags in HTML, in just the right order.
Furthermore, we cannot use ES6 syntax directly in the browsers yet. It first needs to be transformed into ES5 by Babel before serving it to users.
We will be using Gulp and Browserify in this tutorial instead of Webpack. I will not advocate for which tool is better or worse, but I will say that Gulp + Browserify is a lot more straightforward than an equivalent Webpack file. I have yet to find any React boilerplate project with an easy to understand webpack.config.js file.
Create a new file gulpfile.js and paste the following code:
var gulp = require('gulp');
var gutil = require('gulp-util');
var gulpif = require('gulp-if');
var streamify = require('gulp-streamify');
var autoprefixer = require('gulp-autoprefixer');
var cssmin = require('gulp-cssmin');
var less = require('gulp-less');
var concat = require('gulp-concat');
var plumber = require('gulp-plumber');
var source = require('vinyl-source-stream');
var babelify = require('babelify');
var browserify = require('browserify');
var watchify = require('watchify');
var uglify = require('gulp-uglify');
var production = process.env.NODE_ENV === 'production';
var dependencies = [
'react-router',
'underscore'
|--------------------------------------------------------------------------
| Combine all JS libraries into a single file for fewer HTTP requests.
|--------------------------------------------------------------------------
gulp.task('vendor', function() {
return gulp.src([
'bower_components/jquery/dist/jquery.js',
'bower_components/bootstrap/dist/js/bootstrap.js',
'bower_components/magnific-popup/dist/jquery.magnific-popup.js',
'bower_components/toastr/toastr.js'
]).pipe(concat('vendor.js'))
.pipe(gulpif(production, uglify({ mangle: false })))
.pipe(gulp.dest('public/js'));
|--------------------------------------------------------------------------
| Compile third-party dependencies separately for faster performance.
|--------------------------------------------------------------------------
gulp.task('browserify-vendor', function() {
return browserify()
.require(dependencies)
.pipe(source('vendor.bundle.js'))
.pipe(gulpif(production, streamify(uglify({ mangle: false }))))
.pipe(gulp.dest('public/js'));
|--------------------------------------------------------------------------
| Compile only project files, excluding all third-party dependencies.
|--------------------------------------------------------------------------
gulp.task('browserify', ['browserify-vendor'], function() {
return browserify('app/main.js')
.external(dependencies)
.transform(babelify)
.pipe(source('bundle.js'))
.pipe(gulpif(production, streamify(uglify({ mangle: false }))))
.pipe(gulp.dest('public/js'));
|--------------------------------------------------------------------------
| Same as browserify task, but will also watch for changes and re-compile.
|--------------------------------------------------------------------------
gulp.task('browserify-watch', ['browserify-vendor'], function() {
var bundler = watchify(browserify('app/main.js', watchify.args));
bundler.external(dependencies);
bundler.transform(babelify);
bundler.on('update', rebundle);
return rebundle();
function rebundle() {
var start = Date.now();
return bundler.bundle()
.on('error', function(err) {
gutil.log(gutil.colors.red(err.toString()));
.on('end', function() {
gutil.log(gutil.colors.green('Finished rebundling in', (Date.now() - start) + 'ms.'));
.pipe(source('bundle.js'))
.pipe(gulp.dest('public/js/'));
|--------------------------------------------------------------------------
| Compile LESS stylesheets.
|--------------------------------------------------------------------------
gulp.task('styles', function() {
return gulp.src('app/stylesheets/main.less')
.pipe(plumber())
.pipe(less())
.pipe(autoprefixer())
.pipe(gulpif(production, cssmin()))
.pipe(gulp.dest('public/css'));
gulp.task('watch', function() {
gulp.watch('app/stylesheets/**/*.less', ['styles']);
gulp.task('default', ['styles', 'vendor', 'browserify-watch', 'watch']);
gulp.task('build', ['styles', 'vendor', 'browserify']);
If you have not used Gulp before, this is a great starting point —
An Introduction to Gulp.js .
Although the code should be more or less self-explanatory with those task names and code comments, let's briefly go over each task for completeness.
Description
Concatenates all JS libraries into one file.
browserify-vendor
For performance reasons, NPM modules specified in the dependencies array are compiled and bundled separately. As a result, bundle.js recompiles a few hundred milliseconds faster.
browserify
Compiles and bundles just the app files, without any external modules like react and react-router .
browserify-watch
Essentially the same task as above but it will also listen for changes and re-compile bundle.js .
Compiles LESS stylesheets and automatically adds browser prefixes if necessary.
Re-compiles LESS stylesheets on file changes.
Runs all of the above tasks and starts watching for file changes.
Runs all of the above tasks then exits.
Next, we will shift focus to the project structure by creating files and folders that gulpfile.js is expecting.
Step 3. Project Structure
directory create 4 new folders
. Also, download this favicon.png and place it here as well.
newedenfaces
(project root), create a new folder
Then inside
create 4 new folders
components
stylesheets
and 3 empty files alt.js , routes.js and main.js .
stylesheets
directory create a new file main.less which we will populate with styles shortly.
Back in the project root directory (
newedenfaces
), create a new file bower.json and paste the following:
"name": "newedenfaces",
"dependencies": {
"jquery": "^2.1.4",
"bootstrap": "^3.3.5",
"magnific-popup": "^1.0.0",
"toastr": "^2.1.1"
Bower is a package manager that lets you easily download JavaScript libraries, such as the ones specified above, via a command line instead of visiting each individual website, downloading, extracting and adding it to the project manually.
Run bower install and wait for the packages to be downloaded and installed into the
bower_components
directory. You can change that path using the
file, but for the purposes of this tutorial we are sticking with the defaults.
Similarly to
node_modules
, you don't want to commit
bower_components
into a Git repository. But if you do not commit it, how will those files be loaded when you deploy your app? We will get back to this issue during the deployment step of the tutorial.
Copy all glyphicons fonts from
bower_components/bootstrap/fonts
public/fonts
directory.
Download and extract the following background images and place them into
public/img
directory:
Background Images.zip
I have used the Gaussian blur in Adobe Photoshop in order to create that out of focus effect over 3 years ago when I built the original New Eden Faces project, but now it should be totally possible to achieve a similar effect using
CSS filters .
Open main.less that we have just created and paste the CSS styles from the following file. Due to the sheer length of it, I have decided not to include it in this post.
If you have used the Bootstrap CSS framework in the past, then most of it should be already familiar to you.
I have spent many hours designing this UI, tweaking fonts and colors, adding subtle transition effects, so if you get a chance, explore it in greater detail after you finish this tutorial.
I don't know if you are aware of the latest trend to include styles directly inside React components, but I am not sure if I like this new practice. Perhaps when tooling gets better I will revisit this topic, until then I will use external stylesheets like I always have been. However, if you are interested in using modular CSS, check out css-modulesify .
Before we jump into building the React app, I have decided to dedicate the next three sections to ES6, React, Flux basics, otherwise it may be too overwhelming trying to learn everything at once. Personally, I had a very hard time following some React + Flux code examples written in ES6 because I was learning a new syntax, a new framework and a completely unfamiliar app architecture all at once.
Since I cannot cover everything, we will only be going over those topics that you need to know for this tutorial.
Step 4. ES6 Crash Course
The best way to learn ES6 is by showing an equivalent ES5 code for every ES6 example. Again, I will only be covering what you need to know for this tutorial. There are plenty of blog posts that go in great detail about the new ES6 features.
Modules (Import)
import React from 'react';
import {Route, DefaultRoute, NotFoundRoute} from 'react-router';
var React = require('react');
var Router = require('react-router');
var Route = Router.R
var DefaultRoute = Router.DefaultR
var NotFoundRoute = Router.NotFoundR
Using the ES6 destructuring assignment we can import a subset of a module which can be quite useful for modules like react-router and underscore where it exports more than one function.
One thing to keep in mind is that ES6 imports are hoisted. All dependent modules will be loaded before any of the module code is executed. In other words, you can't conditionally load a module like with CommonJS. That did throw me off a little when I tried to import a module inside an if-else condition.
For a detailed overview of the import statement see this MDN page .
Modules (Export)
function Add(x) {
return x +
export default A
function Add(x) {
return x +
module.exports = A
To learn more about ES6 modules, as well as different ways of importing and exporting functions from a module, check out ECMAScript 6 modules and Understanding ES6 Modules .
ES6 classes are nothing more than a syntactic sugar over the existing prototype-based inheritance in JavaScript. As long as you remember that fact, the class keyword will not seem like a foreign concept to you.
class Box {
constructor(length, width) {
this.length =
this.width =
calculateArea() {
return this.length * this.
let box = new Box(2, 2);
box.calculateArea(); // 4
function Box(length, width) {
this.length =
this.width =
Box.prototype.calculateArea = function() {
return this.length * this.
var box = new Box(2, 2);
box.calculateArea(); // 4
With ES6 classes you can also use extends to create a subclass from an existing class:
class MyComponent ponent {
// Now MyComponent class contains all React component methods
// such as componentDidMount(), render() and etc.
For more information about ES6 classes visit Classes in ECMAScript 6 blog post.
var vs let
The only difference between the two is that var is scoped to the nearest function block and let is scoped to the nearest enclosing block - which could be a function , a for-loop or an if-statement block .
Here is a good example showing the difference between var and let :
var a = 5;
var b = 10;
if (a === 5) {
let a = 4; // The scope is inside the if-block
var b = 1; // The scope is inside the function
console.log(a);
console.log(b);
console.log(a); // 5
console.log(b); // 1
Basically, let is block scoped, var is function scoped.
Arrow Functions (Fat Arrow)
An arrow function expression has a shorter syntax compared to function expressions and lexically binds the this value.
[1, 2, 3].map(n =& n * 2); // [2, 4, 6]
[1, 2, 3].map(function(n) { return n * 2; }); // [2, 4, 6]
Parentheses around the single argument are optional, so it is up to you whether you want to enforce it or not. Some see it as a bad practice, others think it's fine.
Besides a shorter syntax, what else is it useful for?
Consider the following example, straight from this project before I converted it to ES6.
$.ajax({ type: 'POST', url: '/api/characters', data: { name: name, gender: gender } })
.done(function(data) {
this.setState({ helpBlock: data.message });
}.bind(this))
.fail(function(jqXhr) {
this.setState({ helpBlock: jqXhr.responseJSON.message });
}.bind(this))
.always(function() {
this.setState({ name: '', gender: '' });
}.bind(this));
Every function expression above creates its own this scope. Without binding this we would not be able to call this.setState in the example above, because this would have been undefined .
Alternatively, we could have assigned this to a variable, e.g. var self = this and then used self.setState instead of this.setState inside the closures .
In any case, here is an equivalent ES6 code using fat arrow functions which preserve original this value:
$.ajax({ type: 'POST', url: '/api/characters', data: { name: name, gender: gender } })
.done((data) =& {
this.setState({ helpBlock: data.message });
.fail((jqXhr) =& {
this.setState({ helpBlock: jqXhr.responseJSON.message });
.always(() =& {
this.setState({ name: '', gender: '' });
Next, let's talk about React, what makes it so special and why should we use it.
Step 5. React Crash Course
React is a JavaScript library for building web user interfaces. You could say it competes against
AngularJS,
Backbone and
Polymer despite being much smaller in scope. React is just the V in the MVC (Model-View-Controller) architecture.
So, what is so special about React?
React components are written in a very declarative style. Unlike the "old way" using jQuery and such, you don't interact with DOM directly. React manages all UI updates when the underlying data changes.
React is also very fast thanks to the Virtual DOM and diffing algorithm under the hood. When the data changes, React calculates the minimum number of DOM manipulations needed, then efficiently re-renders the component. For example, if there are 10,000 rendered items on a page and only 1 item changes, React will update just that DOM element, leaving 9,999 other items unchanged. That's why React can get away with re-rendering the entire components without being ridiculously wasteful and slow.
Other notable features of React include:
Composability , i.e. make bigger, more complex components out of smaller components.
Relatively easy to pick up since there isn't that much to learn and it does not have a massive documentation like AngularJS and Ember.js.
Server-side rendering allows us to easily build Isomorphic JavaScript apps .
The most helpful error and warning messages that I have seen in any JavaScript library.
Components are self- markup and behavior ( and even styles ) live in the same place, making components very reusable.
I really like this excerpt from the React v0.14 Beta 1 blog post announcement that sums up nicely what React is all about:
It's become clear that the beauty and essence of React has nothing to do with browsers or the DOM. We think the true foundations of React are simply ideas of components and elements: being able to describe what you want to render in a declarative way.
Before going any further please watch this awesome video React in 7 Minutes by John Lindquist.
And while you are there, I highly recommend getting the PRO subscription ($24.99/month) to unlock over 94 React and React Native video lessons. No, you will not become an expert just by watching these videos, but they are amazing at giving you short and straight to the point explanations on any particular topic. If you are on a budget, you can subscribe for 1 month, download all videos, then cancel your subscription at the end of the month. Subscribing not only gives you access to React lessons, but also to TypeScript , Angular 2 , D3 , ECMAScript 6 , Node.js and more.
While learning React, the biggest challenge for me was that it required a completely different thinking approach to building UIs. Which is why reading Thinking in React guide is absolutely a must for anyone who is starting out with React.
In similar fashion to the Product Table from Thinking in React , if we are to break apart New Eden Faces UI into components this is what it would look like:
Each component should try to adhere to the
single responsibility principle . If you find yourself working on a component that does too many things, perhaps it's best to split it into sub-components. Having said that, I typically write monolithic components first, just to get it working, then refactor it by splitting it into smaller sub-components.
The top-level App component contains Navbar , Homepage and Footer components. Homepage component contains two Character components.
So, whenever you have a certain UI design in mind, start by breaking it apart from top-down and always be mindful of how your data propagates from parent to child, child to parent and between sibling components or you will quickly find yourself thinking "WTF, how do you do this in React? This would have been so much simpler with jQuery..." .
So, next time you decide to build a new app in React, before writing any code, do this hierarchy outline first. It will help you to visualize the relationships between multiple components and build them accordingly.
All components in React have a render() method. It always returns a single child element. Conversly, the following return statement is invalid because it contains 3 child elements:
render() {
// Invalid JSX,
&li&Achura&/li&
&li&Civire&/li&
&li&Deteis&/li&
The HTML markup above is actually called JSX . As far syntax goes, it is just slightly different from HTML, for example className instead of class to define CSS classes. You will learn more about it as we start building the app.
When I first saw that syntax, I was immediately repulsed by it. I am used to returning booleans, numbers, strings, objects and functions in JavaScript, but certaintly not that. However, JSX is actually just a syntactic sugar. After fixing the code above by wrapping it with a &ul& tag (must return a single element), here is what it looks like without JSX:
render() {
return React.createElement('ul', null,
React.createElement('li', null, 'Achura'),
React.createElement('li', null, 'Civire'),
React.createElement('li', null, 'Deteis')
I think you will agree that JSX is far more readable than plain JavaScript. Furthermore, Babel has a built-in support for JSX, so we don't need to do anything extra. If you have ever worked with AngularJS directives then you will appreciate working with React components, so instead of having two different files — directive.js (logic) and template.html (presentation), you have a single file containing both logic and presentation.
componentDidMount
method in React is the closest thing to
$(document).ready
in jQuery. This method runs once ( only on the client ) immediately after initial rendering of the component. This is where you would typically initialize third-party libraries and jQuery plugins, or connect to Socket.IO.
You will be using Ternary operator in the
method quite a lot: hiding an element when data is empty, conditionally using CSS classes depending on some value, hiding or showing certain elements based on the component's state and etc.
Consider the following example that conditionally sets the CSS class to text-danger or text-success based on the props value.
render() {
let delta = this.props.delta ? (
&strong className={this.props.delta & 0 ? 'text-success' : 'text-danger'}&
{this.props.delta}
&div className='card'&
{this.props.title}
We have only scratched the surface of everything there is to React, but this should be enough to give you a general idea about React as well as its benefits.
React on its own is actually really simple and easy to grasp. However, it is when we start talking about Flux architecture, things can get a little confusing.
Step 6. Flux Architecture Crash Course
Flux is the application architecture that was developed at Facebook for building scalable client-side web applications. It complements React's components by utilizing a unidirectional data flow. Flux is more of a pattern than a framework, however, we will be using a Flux library called Alt to minimize writing the boilerplate code.
Have you seen this diagram before? Did it make any sense to you? It did not make any sense to me, no matter how many times I looked at it.
Now that I understand it better, I am actually really amazed by how such simple architecture can be presented in a such complicated way. But to Facebook's credit, their new Flux diagrams are much better than before.
When I first began writing this tutorial I decided not to use Flux in this project. I could not grasp it for the life of me, let alone teach it to others. But thankfully, I get to work on cool stuff at Yahoo where I get to play and experiment with different technologies during my work hours. Honestly, we could have built this app without Flux and it would have been less lines of code. We don't have here any complex or nested components. But I believe that showing a full-stack React app with server-side rendering and Flux architecture, to see how all pieces connect together, has a value in of itself.
Instead of reiterating the Flux Overview , let's take a look at one of the real-world use cases in order to illustrate how Flux works:
On componentDidLoad (when the page is rendered) three actions are fired:
OverviewActions.getSummary();
OverviewActions.getApps();
OverviewActions.getCompanies();
Each one of those actions makes an AJAX request to the server to fetch the data.
When the data is fetched, each action fires another "success" action and passes the data along with it:
getSummary() {
.get('/api/overview/summary')
.end((err, res) =& {
this.actions.getSummarySuccess(res.body);
Meanwhile, the Overview store (a place where we keep the state for Overview component) is listening for those "success" actions. When the getSummarySuccess action is fired, onGetSummarySuccess method in the Overview store is called and the store is updated:
class OverviewStore {
constructor() {
this.bindActions(OverviewActions);
this.summary = {};
this.apps = [];
panies = [];
onGetSummarySuccess(data) {
this.summary =
onGetAppsSuccess(data) {
this.apps =
onGetCompaniesSuccess(data) {
As soon as the store is updated, the Overview component will know about it because it has subscribed to the Overview store. When a store is updated/changed, a component will set its own state to whatever is in that store.
class Overview ponent {
constructor(props) {
super(props);
this.state = OverviewStore.getState();
this.onChange = this.onChange.bind(this);
componentDidMount() {
OverviewStore.listen(this.onChange);
onChange() {
本文前端(javascript)相关术语:javascript是什么意思 javascript下载 javascript权威指南 javascript基础教程 javascript 正则表达式 javascript设计模式 javascript高级程序设计 精通javascript javascript教程
转载请注明本文标题:本站链接:
分享请点击:
1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
阅读(2099)
孤独,是给你思考自己的时间。
手机客户端
,专注代码审计及安全周边编程,转载请注明出处:http://www.codesec.net
转载文章如有侵权,请邮件 admin[at]codesec.net

我要回帖

更多关于 fullstackreact 的文章

 

随机推荐