• Thế Giới Giải Mã

    Bí ẩn nhân loại Leonardo Da Vinci

  • Thế Giới Giải Mã

    Anh hùng thầm lặng Nikola Tesla

  • Thế Giới Giải Mã

    Thần đèn Thomas Edison

  • Thế Giới Giải Mã

    Người thôi miên Adolf Hitler

Showing posts with label ReactJS Redux. Show all posts
Showing posts with label ReactJS Redux. Show all posts

18 July 2018

ReactJS + Redux: React Router IndexRoute

9-react-router-indexroute:

create-react-app 9-react-router-indexroute
cd 9-react-router-indexroute
npm install redux react-redux redux-logger redux-promise-middleware axios --save
npm install react-router@3 --save

cd src
mkdir actions components containers reducers
npm start
Result

<< Github >>

07 July 2018

ReactJS + Redux: React Router

8-react-router:

create-react-app 8-react-router
cd 8-react-router
npm install redux react-redux redux-logger redux-promise-middleware axios --save
npm install react-router@3 --save

cd src
mkdir actions components containers reducers
npm start
Result
<< Github >>

ReactJS + Redux: List Component

7-user-list-data-readux:

create-react-app 7-user-list-data-readux
cd 7-user-list-data-readux
npm install redux react-redux redux-logger redux-promise-middleware axios --save

cd src
mkdir actions components containers reducers
npm start
Result
<< Github >>

ReactJS + Redux: Redux Containers Call Ajax

6-redux-containers-call-ajax:

create-react-app 6-redux-containers-call-ajax
cd 6-redux-containers-call-ajax
npm install redux react-redux redux-logger redux-promise-middleware axios --save

cd src
mkdir actions components containers reducers
npm start
Result
<< Github >>

ReactJS + Redux: Redux Containers React

5-redux-containers:

create-react-app 5-redux-containers
cd 5-redux-containers
npm install redux react-redux --save

cd src
mkdir actions components containers reducers
npm start
Main
ReatcJS 2018
import React from 'react';
import { render } from 'react-dom';

export default class Main extends React.Component {
    constructor(props){
        super(props);
        this.state = {
            name: "", age: ""
        }
    }
    render() {
        const userList = this.props.data.map( x => {
            return <h1 key= {x.name.toString()} >{ x.name } - {x.age} </h1>
        })
        return(
            <form className="container col-sm-10">
                { userList }
                <div class="form-group">
                    <label for="exampleInputEmail1">Full name</label>
                    <input type="text" placeholder="Input Name" value={this.state.name} onChange={this.onNameChanged} className="form-control"/>
                    <label for="exampleInputEmail1">Age</label>
                    <input type="text" placeholder="Input Age" value={this.state.age} onChange={this.onAgeChanged} className="form-control"/>
                </div>
                <button type="button" onClick={this.onSubmit} className="btn btn-success">Submit</button>
            </form>
        );
    }

    onSubmit = (e) => {
        this.props.onAddUser({name: this.state.name, age: this.state.age})
    }

    onNameChanged = (event) => {
        this.setState({ name: event.target.value });
    }

    onAgeChanged = (event) => {
        this.setState({ age: event.target.value });
    }
}
Actions
ReatcJS 2018
export function addUser(user) {
    return {
        type: 'ADD',
        user: user
    }
}

export function removeUser(user) {
    return {
        type: 'REMOVE',
        user: user
    }
}
Containers
ReatcJS 2018
import { connect } from 'react-redux';
import Main from '../components/Main';
import { addUser } from '../actions/user';

const mapStateToProps = (state) => ({
    data: state,
})
const mapDispatchToProps = (dispatch) => {
    return {
        onAddUser: (user) => {
            dispatch(addUser(user))
        }
    }
}
const UsersContainer = connect(
    mapStateToProps,
    mapDispatchToProps
)(Main)

export default UsersContainer;
Reducers
ReatcJS 2018
export function usersReducer(state = {}, action) {

    switch(action.type) {
        case 'ADD':
            return [...state, action.user]
        default:
            return state
    }
}
Result

<< Github >>

05 July 2018

ReactJS + Redux: Redux Promise

3-async-actions-promises:

create-react-app 3-async-actions-promises
cd 3-async-actions-promises
npm install redux redux-logger redux-promise-middleware axios --save
npm start
Redux Promise
ReatcJS 2018
import { createStore, applyMiddleware } from 'redux';
import { createLogger } from 'redux-logger';
import createPromise from 'redux-promise-middleware';
import axios from 'axios';

const logger = createLogger();
const promise = createPromise();
const middleware  = applyMiddleware(logger, promise);
const store = createStore(userReducer,middleware);

class MyApp extends React.Component {
  constructor(props){
    super(props);
    this.state = {status: '', statusClass: '', name: '', email: '', gender:''}
    store.subscribe(() => {
      const state = store.getState();
      this.setState({name: state.user && state.user.name});
      this.setState({email: state.user && state.user.email});
      this.setState({gender: state.user && state.user.gender});
      this.setState({status: state.status});
      this.setState({statusClass: state.statusClass});
    })
  }
  render() {
    return (
      <div className="container">
        <button className='btn btn-info' onClick={ this.handleGetUser }>New Random User</button>
        <h2 className={ this.state.statusClass }>{ this.state.status }</h2>       
        <h2>{ this.state.name }</h2>
        <h2>{ this.state.email }</h2>
        <h2>{ this.state.gender }</h2>
      </div>
    );
  }
  handleGetUser = (e) => {
    store.dispatch({
        type: 'FETCH_USER',
        payload: axios.get("https://randomuser.me/api")
    });
  }
}
// REDUCER
function userReducer (state = {}, action) {
  const user = {
    name: '',
    email: '',
    gender: ''
  };
  switch (action.type) {
    case 'FETCH_USER_PENDING':
      state = {...state, status: 'Pending...', statusClass: 'text-info'}
      break;
    case 'FETCH_USER_FULFILLED':
      user.name = `${action.payload.data.results[0].name.first} ${action.payload.data.results[0].name.last}`
      user.email = action.payload.data.results[0].email;
      user.gender = action.payload.data.results[0].gender;
      state = {...state,  user, status: 'User Recieved', statusClass: 'text-success'}
      break;
    case 'FETCH_USER_REJECTED':
      state = {...state, status: `${action.payload.message}`, statusClass: 'text-danger'}
      break;
    default:
      return state;
  }
  return state;
}

ReactDOM.render(<MyApp />, document.getElementById('root'));
<< Github >>

ReactJS + Redux: Asyns Actions - Redux Thunk

 2-async-actions:

create-react-app 2-async-actions
cd 2-async-actions
npm install redux redux-logger redux-thunk axios --save
npm start
Asyns actions
ReatcJS 2018
const logger = createLogger();
const middleware  = applyMiddleware(logger, thunk);
const store = createStore(userReducer,middleware);

class MyApp extends React.Component {
  constructor(props){
    super(props);
    this.state = {status: '', statusClass: '', name: '', email: '', gender:''}
    store.subscribe(() => {
      const state = store.getState();
      this.setState({name: state.user && state.user.name});
      this.setState({email: state.user && state.user.email});
      this.setState({gender: state.user && state.user.gender});
      this.setState({status: state.status});
      this.setState({statusClass: state.statusClass});
    })
  }
  render() {
    return (
      <div className="container">
        <button className='btn btn-info' onClick={ this.handleGetUser }>New Random User</button>
        <h2 className={ this.state.statusClass }>{ this.state.status }</h2>       
        <h2>{ this.state.name }</h2>
        <h2>{ this.state.email }</h2>
        <h2>{ this.state.gender }</h2>
      </div>
    );
  }
  handleGetUser = (e) => {
      store.dispatch(dispatch => {
        dispatch({type: 'GET_USER'});
        // ASYNC ACTION
        axios.get('https://randomuser.me/api').then(response => {
          dispatch({type: 'USER_RECIEVED', payload: response.data.results})
        }).catch(error => {
          dispatch({ type: 'ERROR', payload: error})
        })
        dispatch({type: 'AFTER ASYNC ACTION'});
      });
  }
}
// REDCUER
function userReducer(state = {}, action) {
  const user = {
    name: '',
    email: '',
    gender: ''
  };
  switch (action.type) {
    case 'GET_USER':
      state = {...state, status: 'Pending...', statusClass: 'text-info'}
      break;
    case 'USER_RECIEVED':
      user.name = `${action.payload[0].name.first} ${action.payload[0].name.last}`
      user.email = action.payload[0].email;
      user.gender = action.payload[0].gender;
      state = {...state,  user, status: 'User Recieved', statusClass: 'text-success'}
      break;
    case 'ERROR':
      state = {...state, status: `${action.payload.message}`, statusClass: 'text-danger'}
      break;
    default:
      return state;
  }
  return state;
}

ReactDOM.render(<MyApp />, document.getElementById('root'));

ReactJS + Redux: Sử dụng Middleware - Redux Middleware #2

Redux Middleware
ReatcJS 2018
import { createStore, applyMiddleware } from 'redux';
import { createLogger } from 'redux-logger'
// REDCUER
function counterReducer (state = { count: 0 }, action) {
  var nextState = {
    count: state.count
  }
  switch (action.type) {
    case 'ADD':
      nextState.count = state.count + 1
      break;
    case 'MINUS':
      nextState.count = state.count - 1
      break;
    case 'RESET':
      nextState.count = 0
      break;
    default:
      return nextState;
  }
  return nextState;
}
const logger = createLogger();
const middleware  = applyMiddleware(logger);
const store = createStore(counterReducer,middleware );
//Class render
class MyApp extends React.Component {
  constructor(props) {
    super(props);
    this.state = {count: 0};
    store.subscribe(() => {
       console.log("store changed", store.getState())
       this.setState({count: store.getState().count});
    })
  }
  render(){
    return (
      <div className="container">
        <h1>{ this.state.count }</h1>
        <button className='btn btn-success mr-1' onClick={this.handleAdd}>Add</button>
        <button className='btn btn-info mr-1' onClick={this.handleMinus}>Minus</button>
        <button className='btn btn-danger' onClick={this.handleReset}>Reset</button>
      </div>
    );
  }
  handleAdd = (e) => {
    store.dispatch({ type: 'ADD' })
  }
  handleMinus = (e) => {
    store.dispatch({ type: 'MINUS' })
  }
  handleReset = (e) => {
    store.dispatch({ type: 'RESET' })
  }
}
ReactDOM.render(<MyApp />, document.getElementById('root'));

04 July 2018

ReactJS + Redux: Sử dụng Middleware - Redux Middleware


Redux Middleware
ReatcJS 2018
import { applyMiddleware, createStore } from "redux";

const userReducer = (state={}, action) => {
    switch (action.type) {
        case "CHANGE_NAME":
            //state.name = action.payload;
            state = {...state, name: action.payload};
            break;
        case "CHANGE_AGE":
            //state.age = action.payload;
            state = {...state, age: action.payload};
            break;
        case "ERROR":
            throw new Error("Error notification!");
            break;
    }
    return state;
}
const logger = (store) => (next) => (action) => {
  console.log("middleware logger");
  next(action);
}
const error = (store) => (next) => (action) => {
  try{
    next(action);
  } catch(e){
    console.log("middleware error",e);
  }
}

const middleware = applyMiddleware(logger, error);

const store = createStore(userReducer,1,middleware);

store.subscribe(() => {
 console.log("store changed", store.getState())
})
//dispatch action
store.dispatch({type: "CHANGE_NAME", payload: "Antonio"});
store.dispatch({type: "CHANGE_AGE", payload: 45});
store.dispatch({type: "ERROR", payload: 45});

ReactDOM.render(
    <App />,
   document.getElementById('root'));
npm start
Result

ReactJS + Redux: Sử dụng nhiều Reducer - Multiple reducers with redux console

Multiple reducers
ReatcJS 2018
import { combineReducers, createStore } from "redux";

//Reducer lắng nghe các action gọi đến từ dispatch
const userReducer = (state={}, action) => {
    switch (action.type) {
        case "CHANGE_NAME":
            //state.name = action.payload;
            state = {...state, name: action.payload};
            break;
        case "CHANGE_AGE":
            //state.age = action.payload;
            state = {...state, age: action.payload};
            break;
    }
    return state;
}
const contactReducer = (state=[], action) => {
  switch (action.type) {
      case "CHANGE_EMAIL":
          //state.email = action.payload;
          state = {...state, email: action.payload};
          break;
      case "CLEAR":
          //state.age = action.payload;
          state = {...state, email: action.payload};
          break;
  }
  return state;
}
//Nhiều reducers
const reducers = combineReducers({
  user: userReducer,
  contact: contactReducer,
})
//Tạo mới store nội dung là function reducer
const store = createStore(reducers);
//Đăng ký store
store.subscribe(() => {
 console.log("store changed", store.getState())
})
//dispatch action
store.dispatch({type: "CHANGE_NAME", payload: "Antonio"});
store.dispatch({type: "CHANGE_AGE", payload: 45});
store.dispatch({type: "CHANGE_EMAIL", payload: "Antonio@example.com"});
store.dispatch({type: "CLEAR", payload: null});

ReactDOM.render(
    <App />,
   document.getElementById('root'));
npm start
Result

ReactJS + Redux: Basic redux console

Add liblary
npm install
Basic redux console
ReatcJS 2018
import { createStore } from "redux";

//Reducer lắng nghe các action gọi đến từ dispatch
export function reducer(state, action) {
    switch (action.type) {
        case "INC":
            return state + action.payload;
        case "DEC":
            return state - action.payload;
        default: {
            return state;
        }
    }
}
//Tạo mới store nội dung là function reducer
const store = createStore(reducer, 0);
//Đăng ký store
store.subscribe(() => {
 console.log("store changed", store.getState())
})
//dispatch action
store.dispatch({type: "INC", payload: 2});
store.dispatch({type: "INC", payload: 232});
store.dispatch({type: "INC", payload: 65672});
store.dispatch({type: "DEC", payload: 27980780});

ReactDOM.render(
    <App />,
   document.getElementById('root'));
npm start

Result

03 July 2018

ReactJS + Redux: Tạo project React + Redux với Git Command (Git Bash Here)

Tạo project React + Redux với Git Command
ReatcJS 2018
create-react-app react-redux-project    <= Create ReactJS project
clear   <= Xóa console terminal
ls  <= List
cd react-redux-project
ls -la   <= List All
cat package.json   <= Mở xem file
npm start   <= Chạy project
Kết quả
Stop server 
Ctrl + c  <= Với ai chạy server bằng cmd thì chỉ cần bước này
taskkill -F -IM node.exe  <= Với git bash here cần 2 bước này

Download Atom (Dev Tool)
Download Visual Studio Code (Hoặc VS Code)
Download Webstorm (Hoặc WT)

Setup Browser Chrome
React-detector
React Developer Tools

 

BACK TO TOP

Xuống cuối trang