天阔阔雪漫漫共谁同航 这沙滚滚水皱皱笑着浪荡

Business Enterpreneurship

|

Overview

  1. Becoming an entrepreneur:
    • why;
    • discuss the impact of entrepreneurship on people and their local economies;
    • understand simple concepts;
    • difference between a small business owner and an entrepreneur
  2. Identifying an opportunity
    • how business people and entrepreneurs use market research to understand whether their new product or business idea is an opportunity for success.
  3. Creating a business plan
  4. Attracting Investors and obtaining financial support

Voc

  1. Throughtout the course

JavaScript Interview question

|
  1. what is callback function?

    1. define before invoke
    2. high order function, pass as a parameter
    3. mostly implement asychronize
  2. bind, apply&call:
    • bind function want later call
  3. visibility, hidden exist dom tree/none??
  4. block none, not exist

  5. position: fixed, view board, screen

  6. absolute, non-static parent, or screen

  7. box model: order.

  8. selector: .class #(hash, pound)id tagName

  9. prototype, inherit

  10. design pattern, singleton, module,

  11. promise

  12. what is clousure, how to use, example: bank account deposit, withdraw, balance object, two props, a function :blanace

clousure, hide prop, do not want balance are visible

  1. scpoe lagcical 词法zuoyongyu, before browser executed code, we determine scope, each function wil have scope allocate by compiler, lookup parent chain, find nothing, return undefined

  2. use strict,

    1. Javascript 各种, create object, create functions. Javascript closure (不知道) javascript的一些exception和error detection,

object, constructor ``` //a test var Foo = function(a) {
function bar() {
console.log(a); }; this.baz = function() { console.log(a); }; };

Foo.prototype = {  
    biz: function() {    
        console.log(a); 
    }
};

var f = new Foo(7); 
//输出结果:
f.bar(); // result: TypeError, f.bar is not a function.  
f.baz(); // result: 7  
f.biz(); // result: ReferenceError, a: undefined
```
  1. ES6 Good Features(more examples here)

    1. Put the default values of parameters directly in the signature of functions; var link = function(height = 50, color = 'red', url = 'http://azat.co') {...}

    2. Template Literals in ES6: output variables using new syntax ${variableName} inside of the back-ticked string rather than template literals or interpolation;
       var url = `http://localhost:3000/api/messages/${id}`
      
    3. Multi-line strings using back-tick, too.

    4. Destructuring: retrieve prop value of an object, we can use var {name,id} = $('student').data() or works with arrays like:var [col1, col2] = $('.column'),[line1, line2, line3, , line5] = file.split('\n'), rather than writing in two sentences like var stu = $('student').data(), name = stu.name, id = stu.id;. (sweet sugarcoating)

    5. Enhanced object literals: mind blowing now! In ES5, object literals is glorified version of JSON; to ES6, it becomes to something closely resembling classes.

    6. Arrow Functions

    7. Promise??

    8. Block-scoped constructs let and const

    9. Class in ES6 has map, set object??

    10. Modules in ES6: export import with modules

    ``` 概念讨论题:

    1. What is website accessibility and how to improve the accessibility of a website?

    2. Have you ever used any CSS preprocessors? Give the pros and cons of using CSS preprocessor. (谈谈CSS预处理器使用上的经验,比如SASS、LESS之类。分析一下CSS预处理器的优缺点)

    3. Tell me about event bubbling. How could you use it?

6 interview questions on JavaScript

  1. How do you implement an extend function that takes an object & extends it with new properties and makes it work on n levels of recursion? duplicate jquery extend

  2. Write an event emitter base class that allows you to add event listeners? How would you write one that is distributed?

  3. Functions as objects, how does it affect variable scope

  4. What modern frameworks and utilities excite you?

  5. .call() vs. .apply() this keyword is not as predictable as any other languages that function can be applied to other objects and generally be treated as data

  6. Inheritance in javascript: JavaScript inheritance module is unique ally as ob and

  7. Favorite feature in html5 and css3

    • html5 new elements, header footer nav, a bunch of new element, can use canvas, new element for audio and can embed video

    • css3 media query, make website responding to different devices, css3 now has animation now, css box model,

  8. Describe workflow when you are creating webpage

    • First: ps mockup code page html, css, sublime/vscode(code editor) after html/css, using js,

    • Put js at bottom, so the page load faster, imgs are optimized: load faster, minify css, delete useless whitespace, (website accessibility)

    • After finish, make sure the code to w3 standard, check project in different browser or mobile,

  9. Diff css resetting, css normalizing

    • Resetting a way when have h1 or p browser do by default give a margin, padding, resetting remove everything automatically added to elements, so you can define you own style

    • Normalizing, render htm element consistently in the same way in any browsers make sure they have the same style

  10. Diff inline block, block element

    • span{display:inline;}

      • inline element does not accept any width, height attribute,

      • inline accept margin left/right, but no margin top or bottom, allow you to stylize paddings everywhere(four directions)

    • span{display:inline-block;}

      allows you to put width, height, margin ,

    • span{display:block;}

      accept all, take all width, full width, other element will surround it

  11. explain css box model

    an example:
    
    content:
    padding:
    border:
    margin: 
    
  12. What happens if two functions call each other recursively?

    • The recursive calls stop after some time automatically
  13. NaN, undefined

  14. associative array: map, dict, key is unique

  15. Which function returns a part of an array without affecting it? slice(), not join(), concat(),splice()

  16. navigator object represents browser, document the whole dom, document object model

  17. Diff var vs let vs const

    • var has been in js since the beginning; has function scope, do not respect all other blocks except function block; gets hoisted

    • let was introduced recently in ES2015; has block scope, which means a variable defined will die at the end of the block is defined scope or gc

    • const after the first assignment value, you can not assign a new value again. const c; c = 1; we get an error because the first declaration will assign “undefined” to c, but if c is an object, we can modify it like c.push(), add an element to c

  18. Diff triple equal sign vs ==: value and data type, only value

  19. NaN vs undefined

when you not define a variable, an object, js puts a placeholder: undefined, typeof(undefined) -> undefined, typeof(null) -> obuject.

  1. this:

this must belong to an object,

non strict, function is window, this–>window strict

this.bind copy code from original function, this point to first para in bind, call/apply, call immediatly

  1. NaN number,

  2. IIFE, all variables inside are local variables, it will not be changed by outside operations and will not mess up global variables.

  3. require是在React部分问的,所以答AMD是对的,因为AMD(异步加载,异步执行)是浏览器端目前的模块规范,如果是Nodejs,应该回答CommonJS(同步加载,同步执行)。如果问最新规范或者ES6推荐规范,应该回答CMD(异步加载,同步执行)

  4. Angular AngularJS is a toolset for building the framework most suited to your application development. It is fully extensible and works well with other libraries. Every feature can be modified or replaced to suit your unique development workflow and feature needs.

JavaScript

  1. What is the significance of, and reason for, wrapping the entire content of a JavaScript source file in a function block?
  2. This is an increasingly common practice, many JS libraries have adopted this. This technique creates a closure around the entire JS file, this helps to avoid the clashes between different JS modules and libraries.
  3. This technique allows an easily referenceable alias for a global variable. It’s most common in jQuery plugins, used $ to reference jQuery. (function($){})(jQuery)

2: What is callbacks? A callback function is a function that is 1) passed as parameters to another function, and 2) will be invoked after some kind of events. A callback function is a function you provide to another piece of code, allowing it to be called by that code.

  1. What is the advantages of including ‘use strict’ at the beginning of JS file?
  2. Compile time check. Means when you are writing your code, you can easily correct your typos or duplicate declarations.
  3. Eliminates this coercion, prevent accidental globals. like a= 4

  4. What is closure in JS?
  5. A closure is an inner function that has access to the outer function even the outer function has closed.
  6. It provides different methods that could get the data from the parent object scope and return with wantted way.

  7. What are the advantages of using JavaScript?
  8. Less server interaction, improve performance
  9. Immediate feedback to visitors
  10. Increase interactivity with users
  11. Build dynamic User interfaces

  12. Why Javascript is asynchronous.
  13. Javascript is almost all I/O non-blocking, this could be concluded as Web Api’s, Calls such as Ajax, SetTimeOut, Events etc.
  14. CallBack Queue: All the async callback functions or events like onclick are pushed to this queue.
  15. Event loop. There is always one function to look in the stack and queue and if the stack is empty, push the contents from callback queue to the stack.

  16. What is scope chain, hoisting. Hoisting is Javascript’s default behavior of moving the variable and function declarations to the top. Scope chain: When a variable is used, the program traverses the scope chain until it finds an entry for that variable. Redeclaring a variable or passing it into a function is a way of separating it from its previous existence in the scope chain.

  17. Difference between class inheritance and prototype inheritance? Class inheritance: instances inherit from classes, sub-class relationships. It’s a kind of creating tight coupling or hierarchies. Prototypes: instances inheirt directly from other objects. Instances are typically instantiated via ‘Object.create()’. Instances may be composed from many different objects, allowing for easy selective inheritance.

  18. Pros and cons of OOP and FP? OOP Pros: Modularity for easier troubleshooing, Reuse of code through inheritance, flexibility through polymorphism and effective problem solving. cons: Too many relationships to handle, OOP depends on shared state. Lead to undesirable behavior such as race conditions FP pros: Avoid any shared state or side-effects, eliminates the race conditions for the same resources. Instead of concentrate on what to do, letting the underlying functions take care of the how. This leaves tremendous latitude for refactoring and performance optimization. FP Cons: Over exploitation of FP features such as point-free style and large compositions can potentially reduce readability because the resulting code is often more abstractly specified, more terse, and less concrete.

  19. What is this, how to change the ownership of this? This refers to the object that owns this code. The value of this is determined by how a function is called. There are two ways to manually set this value. They are .apply() and .call() . .apply and .call have very small difference. For both of them, the first argument must be this, and the second parameter for .apply is [], but .call can accept any arguments.

  20. Bind vs Call vs Appliy? https://stackoverflow.com/questions/15455009/javascript-call-apply-vs-bind https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind Use .bind() when you want that function to later be called with a certain context, useful in events, and bind() function creates a new bound function(BF), that wraps the original function object. Use .call() or .apply() when you want to invoke the function immediately, and modify this value. For bind(), we use it primarily to call a funtion with this value set explicitly. Bind() allows us to easily set which specific object will be bound to this when a function or method is invoked.

  21. What is event bubbling? Event bubbling directs an event to its intended target, it works like this
  22. a button is clicked and the event is directed to the button
  23. if an event handler is set for that object, the event is triggered
  24. if no event handler is set for that object, the event bubbles up to the objects parent And event bubbles up from parent to parent until it is handled or it reaches the document object.

  25. Good features of ES6. https://webapplog.com/es6/ Default Parameters in ES6 : var height = height || 50; Template Literals in ES6: ${syntax} in back stick expression Multi-line Strings in ES6 Destructuring Assignment in ES6 Enhanced Object Literals in ES6 Arrow Functions in ES6 Promises in ES6 Block-Scoped Constructs Let and Const Classes in ES6, has Map, Set object Modules in ES6: export import with modules

  26. What is controlled & uncontrolled component? Controlled component is a component where React is in control and is the single source of truth for the form data. Uncontrolled component is where your form data is handled by the DOM, instead of inside your React component.

  27. Javascript inheritance? Javascript has only one construct: object. Each object has a private property (prototype) which holds a link to another object called its prototype. And that prototype object has its own prototype, and so on until an object reached null as its prototype. Also null is the final link in the prototyp chain.

  28. What is promise? Promise is a JavaScript object used to handle asynchronized operations, and the result would be get in the future. To avoid loop hell, nested functions It has 3 states: pending, fullfilled, rejected. A common need is excute 2 or more asynchronous operations, where each subsequent operation starts when the previous operation succeeds, with the result from previous step. We accomplish this by creating a promise chain instead of two many nested functions. doSomething(function(result) { doSomethingElse(result, function(newResult) { doThirdThing(newResult, function(finalResult) { console.log(‘Got the final result: ‘ + finalResult); }, failureCallback); }, failureCallback); }, failureCallback); ————————————————————————- doSomething().then(function(result) { return doSomethingElse(result); }) .then(function(newResult) { return doThirdThing(newResult); }) .then(function(finalResult) { console.log(‘Got the final result: ‘ + finalResult); }) .catch(failureCallback); From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises

  29. What is map and reduce? The map() method creates a new array with the results of calling a provided function on every element in the calling array. The reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.

  30. What is curry and compose? First, currying is translating a function that takes multiple arguments into a sequence of functions, each accepting one argument. Notice the distinct way in which a curried function is applied, one argument at a time. Second, function composition is the combination of two functions into one, that when applied, returns the result of the chained functions. It’s very common practise in React, ex. React middle ware, that uses enhancer to compose a list of middle ware, and works like a work flow to pass the states. The two concepts are closely related as they play well with one another.

  31. Local storage, Cookie session storage
    • Cookie: all browser information in client side
    • Local storage and session storage. session-temp; local-permanent

Some great articals

  1. About perfermance: Best Practices for Speeding Up Your Web Site
more code in interview-xy

Get Start with Mongodb

|

Databases

  1. database: can have relations between tables

  2. relational db – non-relational db, tables – collections, object – document

Mongodb

  1. Find how to download on mongodb website, install using homebrew is recommended.

  2. which mongo check the installation directory of mongodb

  3. Node.js: a platform

  4. Packages in node: file, request handling, express

  5. Run mongodb on mac: mongod

    • if it shutting down, maybe permission problem, using sudo su, then mongod

    • in a new terminal, mongo, it is running

  6. Insert examples: db.collectionName.functionName

     //insert 1
     db.trainees.insert({
         "id":2,
         "name":"yy2",
         "place":"nj2",
         "phone":"1232"
     })
    
     //insert many
     db.trainees.insertMany([
         {
             "id":12,
             "name":"yy12",
             "place":"nj12",
             "phone":"12312"
         },
         {
             "id":11,
             "name":"yy11",
             "place":"nj11",
             "phone":"12311"
         }
     ])
    
  7. Retrieve examples

     //retrieve and format
     db.trainees.find().pretty()
    
  8. Find specific document

     db.trainees.find({"id":1,"place":"nj"}).pretty()
     //or
     db.trainees.find({
         $or:[
             {"id":11},
             {"place":"nj"}
         ]
         }).pretty()
    
  9. Limit show what props of result, second param in find(), "_id":0 hide the auto-id

     db.trainees.find({},{"id":1,"place":"nj","_id":0}).pretty()
    
  10. More $

    db.trainees.find({ "id":{$gt:2}}).pretty()
    db.trainees.find({ "id":{$in:[1,11]}}).pretty()
    
  11. Update: set

     db.trainees.update({"id":12},{
                $set:{
                    "name": "newname"
                }
            })
    db.trainees.update({"id":12},{
            $set:{
                "org": "xyorg"
            }
        })
     db.trainees.update({},{
            $set:{
                "org": "xyorg"
            }
        },{"multi":true})
    //unset
     db.trainees.update({},{
            $unset:{
                "org": ""
            }
        },{"multi":true})
    
  12. remove

    db.trainees.remove({"id":12});
    

Front end Demos

|

React Course and Build a Book Store

|

Udemy course

1. why redux

  1. Application state, store all components’ state, children components get these states by this.props.

  2. State container, store application states.

  3. Setup:

  4. Workflow:

    store(create and maintain states)–>

    provider(passing down store as props)–>

    actions(fire actions to update states)–>

    middleware(optional, useful when create a kind of chain of action when the action reaches the user which evaluates what to do with the action)–>

    reducers(update the data in the store which then updates the app)–>

    store(so on in a cycle)

  5. Middleware: hook function

2. setup

  1. Install express, webpack, babel

     npm init
     npm i --save express
     npm i --save webpack
     npm i --save babel-core babel-loader babel-preset-es2015 babel-preset-stage-1 babel-preset-react
     npm i --save redux
    
  2. Design file tree:

     -- AppFile
         - node_modulus(folder)
         - public(folder)
             - index.html//include bundle.js in script tags
         - src(folder)
             - app.js
         - package.json
         - server.js
         - webpack.config.js   
    
  3. Write server.js

    • require() function

      • loads a module and assigns it to a variable for your application to use

      • to access functionality located in other files in your project.

      • In Node module system each of your javascript file is a module and can expose functionality to be required by other files.

    • Express:

      • Express in nodejs is a framework which provides features like: Middlewares to respond to your request, Routing, Render html web pages.

      • Routing: handle multiple url context in a website, or how they respond to client requests.

      • Route paths can be strings, string patterns, or regular expressions.

      • Middleware functions are functions that have access to the request / response objects, and the next middleware function in the application’s request-response cycle.

      • Serving Static Files: Express provides a built-in middleware express.static to serve static files, such as images, CSS, JavaScript etc

    • Using “use strict” directive to make sure you receive an error, writing js need to specify “use strict”, writing jsx, use strict is default

    • So the server.js is like:

        "use strict"
        var express = require('express');
        var app = express();
        var path = require('path');
      
        //middleware to define folder for strict files or images
        app.use(express.static('public'));
      
        //catch the main route, send back response in index.html
        app.get('/', function(req,res){
            res.sendFile(path.resolve(__dirname,'public','index.html'))
        });
      
        app.listen(3000,function(){
            console.log('listening 3000');
        });
      
  4. Config webpack, webpack.config.js

    • We make our module available outside using module.exports

    • Watch: true. So that every time we save our changes in one of the files are linked with the app.js, webpack will recompile the bundle file automatically

    • scan all js files, to prevent long compile time, we exclude the old js files inside node_modules

     var path = require('path');
     const webpack = require('webpack');
    
     module.exports = {
         //path of our js file; 
         entry: './src/app.js',
         output: {
             filename: 'bundle.js',
             path: path.resolve(__dirname,'public')
         },
         watch: true,
         module:{
             loaders:[
                 {
                     test: /\.js$/,
                     exclude: /node_modules/,
                     loader: 'babel-loader',
                     query: {
                         presets: ['react','es2015','stage-1']
                     }
                 }
             ]
         }
     }
    
  5. Start. Start node and webpack, go to localhost:3000

     node server.js
     webpack
    

3. Create app

  1. Import createStore module from redux

  2. Create store using reducer

    • Pass the reducers as argument to create store

    • See what the store’s current state, using subscript method

    • Lock the result using store.getState()

  3. Create and dispatch actions

    • An action is made by an object that has two properties: type and payload

    • Type is a keyword in redux, but payload you can call it as you wish

    • Create a counter : store.dispatch({type:"INCREMENT", payload:1})

  4. Define reducers

    • Create reducer by passing two arguments, state and action

    • reducer is used to evaluate what to du when they receive an action

  5. Try the subscribe method, our listener in app.js

     "use strict";
     import { createStore } from "redux";
    
     //step 3 define reducers in order to create the store
     //create reducer by passing two arguments, set the initial value for the state
     //set initial value to state in function()
     //the use of reducers are evaluate what to do using switch
     const reducer = function(state = 0, action) {
     console.log("reducer...state: ", state, "action: ", action);
     switch (action.type) {
         case "INCREMENT":
         return state + action.payload;
         break;
         case "decrement":
         return state - action.payload;
         break;
     }
     return state;
     };
    
     //step 1 create the store, pass reducers as parameter
     //see the current of store, use the subscript method, add listener,
     const store = createStore(reducer);
     console.log("store: ", store);
     store.subscribe(function() {
     console.log("current state: " + store.getState());
     });
    
     //step 2 create and dispatch actions
     //an action is made by an object that has two properties, type and payload
     //type, key words in redux, payload, call it as you wish
     store.dispatch({ type: "INCREMENT", payload: 1 });
    
     store.dispatch({ type: "INCREMENT", payload: 1 });
    
     store.dispatch({ type: "decrement", payload: 1 });
    
  6. When we have complex payload with actions:

     "use strict";
     import { createStore } from "redux";
    
     //reducer
     //when payload is an array, state = [], when payload only have one obj, state = {}
     const reducer = function(state = [], action) {
     switch (action.type) {
         case "post_book":
         return state = action.payload;
         break;
     }
     return state;
     };
    
     //store,state
     const store = createStore(reducer);
     store.subscribe(function() {
     // console.log("current state: " , store.getState().price);
     //when the payload is an array:
     console.log("current state: " , store.getState()[1].price);
    
     });
    
     //action
     store.dispatch({
     type:"post_book",
     payload:[
         {
         id:1,
         title:'book title',
         description:'im a book',
         price:10000
         },
         {
         id:2,
         title:'book title2',
         description:'im another book',
         price:10002
         }
     ]
     });
    
  7. CRUD operations, (create, read, update, delete)
     const reducer = function(state = {books:[]}, action) {
         switch (action.type) {
             case "post_book":
             //we want add third book in, with out this concat, third book overwrite previous payload,
             //never use push to concatenate array in redux, use concat method, 
             //because, push is a mutable, in redux, should never mutate the state
             // let books = state.books.concat(action.payload);
             // return {books};
             return {books:[...state.books,...action.payload]}
             break;
         }
         return state;
     };
    

    destruct??

  8. Pure function, give the same input, always output the same output. Reducer should be pure function.

  9. Three principles of redux

    1. Single source of truth: the state of whole app is stored in an object tree within a single store(under one object - state)

    2. States are read-only: The only way to change the state is to emit an action

    3. Changes are made with pure functions: reducers hae to be pure functions

  10. prevent mute state mutation.

    1. Operate arrays: concat(), slice() or …spread operator, push(),splice()

    2. Operate objects: Object.Assign() or …spread operator

  11. Delete

    //when all in one file
    //action, we can write a sequence dispatches of actions
    store.dispatch({
        type:"post_book",
        payload:[
            {
            id:1,
            title:'book title',
            description:'im a book',
            price:10000
            },
            {
            id:2,
            title:'book title2',
            description:'im another book',
            price:10002
            }
        ]
    });
    
    //we using logger,so we can remove subscribe method
    const store = createStore(reducers, middleware);
    store.subscribe(function() {
        console.log("current state: " , store.getState());
        // console.log("current state: " , store.getState().price);
        // when the payload is an array:
        // console.log("current state: " , store.getState()[1].price);
    
        });
    
    store.dispatch({
        type:"post_book",
        payload:[
            {
            id:3,
            title:'book title3',
            description:'im a 3rd book',
            price:10003
            },
        ]
    });
    store.dispatch({
        type:"delete_book",
        payload:{id:1}, 
        });
    
        store.dispatch({
        type:"update_book",
        payload:
            {
            id:2,
            title:'book title updated'
            }
    });
    
    store.dispatch({
        type:"add_to_cart",
        payload:[{id:1}]
        });
    
    
    //reducer
    //when payload is an array, state = [], when payload only have one obj, state = {}
    const reducer = function(state = {books:[]}, action) {
        switch (action.type) {
            case "post_book":
            //we want add third book in, with out this concat, third book overwrite previous payload,
            //never use push to concatenate array in redux, use concat method, 
            //because, push is a mutable, in redux, should never mutate the state
            // let books = state.books.concat(action.payload);
            // return {books};
            return {books:[...state.books,...action.payload]}
            break;
            case "delete_book":
            const currentBookToDelete = [...state.books];
            const indexToDelete = currentBookToDelete.findIndex(
                // (book)=>{book.id===action.payload.id;}
                function(book){
                return book.id===action.payload.id;
                }
            )
                    console.log("delete",action.payload.id);
    
            return {books:[...currentBookToDelete.slice(0,indexToDelete),
                ...currentBookToDelete.slice(indexToDelete+1)]}
            break;
            case "update_book":
            const currentBookToUpdate = [...state.books];
            const indexToUpdate = currentBookToUpdate.findIndex(
                // (book)=>{book.id===action.payload.id;}
                function(book){
                return book.id===action.payload.id;
                }
            );
            const bookToUpdate = {
                ...currentBookToUpdate[indexToUpdate],
                title:action.payload.title
            };
                    console.log("update",bookToUpdate);
    
            return {books:[...currentBookToUpdate.slice(0,indexToUpdate),bookToUpdate,
                ...currentBookToUpdate.slice(indexToUpdate+1)]}
            break;
    
        }
        return state;
    };
    
  12. Separate actions and reducers: shopping cart, in one file, easy to understand, but code become hard to maintain, solution: separate into different files, use reducer.combine(),

  13. Notice: when import, {}, find the obj in {} from ‘’, without {} means import the obj which is export in ‘’ and name it as ..

    • eg: import reducers from './reducers/index'; vs. import {addToCart} from './actions/cartActions'; name the export object in index as reducer; import addToCart, which is in cartActions.
  14. Middleware(optional): implement a state logger to save state and show it pretty. we using logger,so we can remove store.subscribe method

    1. install: npm i --save-dev redux-logger

    2. add

       import { applyMiddleware, createStore } from "redux";
       import logger from 'redux-logger';
      
       const middleware = applyMiddleware(logger);
       const store = createStore(reducers, middleware);
      

2. Create app

  1. Install react : npm i --save react, and thennpm i --save react-dom, and ` npm i –save react-redux, and npm i –save react-router`

  2. Render a class in html

     render(
         <BooksList />, document.getElementById('app')
     )
     //in class BooksList(bookList.js):
     class BooksList extends React.Component{
    
         render(){
             return (
                 <div>
                     <h1>hi react-xy</h1>
                 </div>
             )
         }
     }
    
    
  3. Redux + React: it will make the redux store available in react, we need the redux component called provider, the provider wraps the entire react app and pass the store as props to react component.

  4. Connect react and redux: when pass mapStateToProp as an argument to connect(), component is subscribing to the store, by doing this, returns the updated states to our local component

  5. Dispatch actions:

    1. export function in bookActions.js

    2. deal with action in bookReducer.js

    3. connect in component: bookList.js

  6. Design shopping cart

    1. react-bootstrap, recommended, translate bootstrap into pure react component $ npm install --save react-bootstrap
  7. Architecture

    • main.js

      • menu.js

      • footer.js

      • booksList.js: a list of books, bookItem.js+cart.js

      • booksForm.js

      • about.js

      • contacts.js

  8. Create bookItem component

    • title,

    • description

    • price

    • buy now btn

  9. Create bookForm component: Add post request

  10. Create cart

Note

  1. virtual DOM, only update the changed element.
  2. babel, jsx javascript compile engine
  3. redux framework, flux