+1

Getting start Reactjs with Redux part 1

In this article I will show and introduce you about reactjs and redux : important thing and how them work before go to build real app using Reactjs and Redux.

I What is Redux?

Redux is a framework that controls states in a JavaScript app. it is a front-end libraries used to manage state applications in JavaScript. It is described as a predictable state container, Redux management state of the entire application in a state tree object and can not change it directly. When there is a change, a new object will be created by the actions and reducers. Now let’s start understand the components in Redux:

Action: Action is the event, the Action sends data from the application to store. Store will be responsible for extracting information from the actions., The action itself is simple JS object attributestype. There must be an action typeto indicate the action that is being executed. type Can be a string or a const

 export function selectBook(book) {
         return {
             type: 'BOOK_SELECTED',
              payload: book
        }
    }

Reducers: Reducer is responsible for the application state changes only in response or otherwise function Reducers are responsible for taking former state status, an action and return a new state.

  • In a complex application using functions combineReducers()to combine all reducersinto a single index in the reducer application. Each reducers represent part of the application state, and each state a reducer, there are different parameters.

  • combineReducers() utinity make the structure more Maintain files easier.

  • If an object changes state only a few values, Redux will create a new object, but not change values will still refer to the old object and only the new value of the newly created new object. That increases efficiency for perfonrmance.

export default function (state , action) {
      switch (action.type) {
        case 'BOOK_SELECTED':
          return action.payload;
      }
      return state;
    }

Store: Store is an application object that it holds state and provide some helper methods to access the state, dispatch actions and registered listeners. The entire state is represented by a single store.

Tasks of the store

  • Keep application state
  • Access to the state through getState()
  • Allows state updates throughdispatch(action)
  • Register listenders through subscriber(listener)
  • Handling unregister listeners through function unsubscribe(listener)

You have only one store in Redux application, when you want to split the data processing logic will use compsition reducer instead of many stores.Very easy to store when you've got reducer, we use the function combineReducers() to combine these into a single reducers, and will import them via functionscreateStore().

Life cycle of an application: The life cycle of an application is composed of 4 steps Redux

Call store.dispatch(action)

An action plan is an object that describes what happened.

    { type: 'LIKE_ARTICLE', articleId: 12 }
    { type: 'FETCH_USER_SUCCESS', response: { id: 4, name: 'Kane' } }
    { type: 'ADD_TODO', text: 'Writing article.' }

You can call store.dispatch(action)from anywhere in the application, including components, XHR callback .. Redux store gọi reducer fuction

Store sends to reducer 2 parameters: current state and the action tree.

 let previousState = {
   visibleTodoFilter: 'SHOW_ALL',
   todos: [
     {
       text: 'Writing article.',
       complete: false
     }
   ]
 }
 let action = {
   type: 'ADD_TODO',
   text: 'Understand the flow.'
 }
 let nextState = todoApp(previousState, action)

Note that a reducer is a pure function, it calculates the next state, it does not implement any other actions such as transitions API call or router. They should be executed when a acction distention is dispatch. Root reducer output can be combined into a single reducers of many state tree

Redux has a helper function combineReducers(), it is useful to subdivide the function of the function of state management of tree branches Redux store the entire state tree saved is returned by root reducer.

This new tree state is the new state of the application. Each listener registered to store.subscribe(listener) will be called. Listenter can call store.getState() to get the current state

II. What is React?

React.js is a Javascript library is emerging in recent years the trend Single Page Application. While other frameworks attempt towards a complete MVC model, the outstanding React with a simple and easy to coordinate with other JavaScript libraries.Today we will learn the basic concepts of React

React is what?

React is a UI development library in Facebook to support the construction of the components (components) with interactive UI, with status and can be reused. One of the attractions of the library React not only work on the client, but also to render on the server and can connect with each other. React use DOM concepts (Virtual DOM) to select and render the node-based element of the state name change makes us just change few components as possible to keep the DOM updates.

JSX Javascript snippet on the JSX and it's called the move from Javascript XML syntax. JSX lets you write JavaScript HTML style.For normal html tag, attribute classcalled classNameand foris htmlForas these are available from specified.

Without using the syntax JSX will look like this code:

React.render(
  React.createElement('h1', null, 'Hello!'),
  document.getElementById('myDiv')
);

Components

When using the method renderwith DOM React as above, the first argument is the component we want to render, and the second argument is the DOM node it is set up. We can use the method createClassto create the component class. It may get some value from an object as argument.

var MyComponent = React.createClass({
    render: function(){
        return (
            <h1>Hello, world!</h1>
        );
    }
});

After creating a class, we can render it in the document as shown below:

ReactDOM.render(
    <MyComponent/>,
    document.getElementById('myDiv')
);

Props

When using our components, we can add attributes called props. These attributes are called out in the components with this.propsand can be used in methods renderto render dynamic data.

var MyComponent = React.createClass({
    render: function(){
        return (
            <h1>Hello, {this.props.name}!</h1>
        );
    }
});
ReactDOM.render(<MyComponent name="Handsome" />, document.getElementById('myDiv'));

Lifecycle methods

  • componentWillMount - Called once on both the client and server before rendering takes place.
  • componentDidMount - Called on the client only once, after rendering.
  • shouldComponentUpdate - Return value to decide if the component has not been updated.
  • componentWillUnmount - Called before separating component.
  • getInitialState - Returns the initial value of the state.
  • getDefaultProps - Get props props default if not provided.
  • mixins- A sequence of objects used to extendthe features of the component.

Status (state)

Every component has a state and an object object props. State is set to use the method setState. Call setStateactivation UI updates and activities associated with the React. If we want to set an initial state before the engagement, we can use the method getInitialState.

var MyComponent = React.createClass({
    getInitialState: function(){
        return {
            count: 5
        }
    },
    render: function(){
        return (
            <h1>{this.state.count}</h1>
        )
    }
});

Events

React has a usable system events in different browsers. These events are attached as part of the components and can enable the method.

var Counter = React.createClass({
  incrementCount: function(){
    this.setState({
      count: this.state.count + 1
    });
  },
  getInitialState: function(){
     return {
       count: 0
     }
  },
  render: function(){
    return (
      <div class="my-component">
        <h1>Count: {this.state.count}</h1>
        <button type="button" onClick={this.incrementCount}>Increment</button>
      </div>
    );
  }
});

ReactDOM.render(<Counter/>, document.getElementById('mount-point'));

IV. Conclusion

In this article I just introduce to all you to getting start reactjs and redux and the next article I will show you to build app reactjs with redux.


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí