React simple introduction, reactredux simple demo

Source: Internet
Author: User

React simple introduction, reactredux simple demo

React background

React is a JavaScript library used to build user interfaces. It is mainly used to build the UI, rather than an MVC framework. However, you can use React as the View layer of the MVC Architecture to easily use it in existing projects, it is a JavaScript library used to build user interfaces. It originated from Facebook's internal project and was used to build Instagram websites. It was open-source in May 2013. React has high performance and the code logic is very simple. More and more people are paying attention to and using it.

In the past, when there was no ajax technology, the web page was rendered from the server to html output to the browser side for rendering. Similarly, a user's page change operation will refresh the entire page to complete. Until ajax appears, partial page refresh is implemented, and the efficiency and separation brought by this will surprise web developers. However, complicated user interaction and presentation require a large number of DOM operations, which leads to new bottlenecks in page performance and development efficiency.

Today, we are familiar with front-end performance optimization, DOM elements reduction, reflow and repainting reduction, and DOM query as much as possible during the coding process. Any UI changes on the page are implemented through overall refresh. Fortunately, React uses its own DOM Diff algorithm to calculate the differences between the current version and the new version of the virtual page, minimizing re-painting and avoiding unnecessary DOM operations, it solves these two recognized front-end performance bottlenecks and achieves efficient DOM rendering.

We know that the performance consumption caused by frequent DOM operations is very high, and React is fast because it does not directly operate the DOM, but introduces the implementation of virtual DOM to solve this problem.

For page updates, React compares and updates differences through its own DOM Diff algorithm, reflecting that the page only redraws the updated part, thus improving rendering efficiency.

NOTE: For the following performance descriptions, refer to ziyou Yuxi.

For React performance, I would like to say a few words:

1. React never said "React is faster than native DOM operations ". The Basic Thinking Mode of React is to re-render the entire application every time there is a change. If there is no Virtual DOM, simply reset innerHTML.

2. In terms of performance comparison, we need to clearly distinguish between initial rendering, a small amount of data updates, and a large amount of data updates.

3. Do not naively think that Virtual DOM is fast, diff is not free, and the real value of Virtual DOM is never performance, but it

1) opened the door for functional UI programming;

2) scenes other than DOM can be rendered, such as backend and native.

Componentization

In business development, when we encounter a public template, We have to couple the template with the specified data format to implement the component. In React, we can use JSX syntax to encapsulate components and aggregate the structure, data logic, and even styles of components to define components more easily, clearly, and intuitively.

With the implementation of componentization, We can intuitively split a complex page into several independent components, and then combine these independent components to complete a complex page. This reduces the logic complexity and achieves code reuse.

React Basics

Template

<! DOCTYPE html> example 

JSX

In the code in the previous section, the HTML language is directly written in the JavaScript language without any quotation marks. This is the JSX syntax, which allows mixed HTML and JavaScript writing.

Benefits of JSX:

1. What are the advantages of using JSX syntax to encapsulate components:

1) familiar code

2) More semantic

3) more abstract and intuitive

2. Notes:

1) In the render method, the top-level element of return can only be one;

2) If you want to define a style, you cannot write it like this.
// Do not see similar errors, style = "opacity: {this. state. opacity };"

3) Use className and htmlFor to replace the corresponding class and

Tip: if you are interested in componentization, you can continue to follow Vuejs, Web components, and other component writing methods. /** With the emergence of more complex multi-terminal environments, there is still more room for imagination about component standardization. The definition of React components is not the end point, nor must it be the standard, however, it will leave a profound de impact on the componentization path. **/

JSX basic syntax:

  var names = [‘Alice', ‘Emily', ‘Kate'];

  ReactDOM.render(
    <div>
    {      names.map(function (name,key) {
      return <div key={key}>Hello, {name}!</div>
    })    
}
    </div>,        document.getElementById(‘example')
  );

The code above demonstrates the basic syntax rules of JSX: When an HTML Tag (starting with <) is encountered, it is parsed using HTML rules. When a code block (starting with {) is encountered, it is parsed using JavaScript rules.

JSX allows you to insert JavaScript variables directly in the template. If this variable is an array, all the members of this array are displayed.

var arr = [
    

Components

1. Concept

React allows code to be encapsulated into a component, and then insert the component into the webpage like inserting a common HTML Tag. The React. createClass method is used to generate a component class.

2. Sample Code

var HelloMessage = React.createClass({  render: function() {    return 

This. props. children

This. attributes of the props object correspond to the attributes of the component one by one, but an exception is the this. props. children attribute. It indicates all child nodes of the component.

Var NotesList = React. createClass ({render: function () {return (<ol> {/** because this. props. the return value of children will return undefined, object, array. * therefore, react provides a react. the Children method specifically handles this. props. children **/React. children. map (this. props. children, function (child) {return <li >{ child }</li >;}</ol>) ;}}; ReactDOM. render (<NotesList> <span> hello </span> <span> world </span> </NotesList>, document. getElementById ("example "));

PropTypes

The component attributes can accept any value, including strings, objects, and functions. Sometimes, we need a mechanism to verify that the parameters provided by others when using components meet the requirements. The PropTypes attribute of the component class is used to verify whether the attributes of the component instance meet the requirements.

Var MyTitle = React. createClass ({propTypes: {/** declares that the title attribute is required and the data type must be a string, which is equivalent to the canonicalized interface document **/title: React. propTypes. string. isRequired,}, render: function () {return 

 Error example:

var data = 123;ReactDOM.render( <MyTitle title={data} />, document.body);

Getdefaproprops

The getdefaproprops method can be used to set the default value of component properties.

var MyTitle = React.createClass({    getDefaultProps: function () {      return {        title:”hello world”      }    },    render: function() {      return 

Get real DOM nodes

A component is not a real DOM node, but a Data Structure in the memory, called virtual DOM ). It becomes a real DOM only after being inserted into a document. According to the React design, all DOM changes occur on the virtual DOM first, and then the actual changes are reflected on the real DOM. This algorithm is called DOM diff, it can greatly improve the performance of web pages.

var MyComponent = React.createClass({  handleClick: function() {    this.refs.myTextInput.focus();  },  render: function() {    return (    <div>    <input type=“text” ref=“myTextInput” />    <input type=“button” value=“Focus the text input” onClick={this.handleClick} />    </div>    );  }});ReactDOM.render(<MyComponent />,    document.getElementById(‘example'));

This. state

Components inevitably need to interact with users. A major innovation of React is to regard components as a state machine, with an initial state at the beginning, and then user interaction, resulting in status changes, this triggers re-rendering of the UI. React regards a component as a State machine ). Through interaction with users, different states are implemented, and the UI is rendered to make the user interface and data consistent. In React, you only need to update the state of the component and then re-render the user interface based on the new state.

Var LikeButton = React. createClass ({getInitialState: function () {/** initial value of the set state **/return {liked: false} ;}, handleClick: function () {/** change status **/this. setState ({liked :! This. state. liked}) ;}, render: function () {var text = this. state. liked? 'Like': 'dislike'; return (<p onClick = {this. handleClick}> you {text} him. click to switch. </p>) ;}}); ReactDOM. render (<LikeButton/>, document. getElementById ('example '));

Because this. props and this. state are both used to describe the features of components, confusion may occur. A simple differentiation method is that this. props represents those features that will not be changed once defined, and this. state is a feature that will change with user interaction.

var Input = React.createClass({  getInitialState: function() {    return {value: ‘Hello!'};  },  handleChange: function(event) {    this.setState({value: event.target.value});  },  render: function () {    var value = this.state.value;    return (    <div>    <input type=“text” value={value} onChange={this.handleChange} />    <p>{value}</p>    </div>    );  }});ReactDOM.render(<Input/>, document.body);

Component API

Seven methods of components:

Set status: setState;

Replacement status: replaceState;

Set the property setProps;

ReplaceProps;

Force update: forceUpdate;

Get DOM node: getDOMNode;

Determine the mounting status of the component: isMounted.

Component lifecycle

Initialization

Getdefaproprops: Set the default value

GetInitialState: Set the initial state.

ComponentWillMount: (The component will be loaded soon)

Render (rendering)

ComponentDidMount: the component has been loaded and will only start when the first component is called.

Running

ComponentWillReceiveProps

ShouldComponentUpdate is called before it receives a new props or state. This method is not called during initialization rendering.

Before componentWillUpdate render is triggered, update

Render Rendering

ComponentWillUnmount is called immediately when the component is removed from the DOM.

Destroy

ComponentWillUnmount is called immediately when the component is removed from the DOM.

var Hello = React.createClass({  getInitialState: function () {    return {      opacity: 1.0    };  },  componentDidMount: function () {    this.timer = setInterval(function () {      var opacity = this.state.opacity;      opacity -= .05;      if (opacity < 0.1){        opacity = 1.0;      }      this.setState({        opacity: opacity      });    }.bind(this), 100);  },  render: function () {    return (    <div style={{opacity: this.state.opacity}}>    Hello {this.props.name}    </div>    );  }});ReactDOM.render(<Hello name=“world”/>,    document.body);

Because the React component style is the first braces of an object, it indicates that this is JavaScript syntax, and the second major bracket indicates the style object.

Ajax

The above Code does not use jQuery to complete Ajax requests for ease of instruction. The React itself does not have any dependencies. You can use other libraries instead of jQuery.

var Input = React.createClass({  getInitialState: function () {    return {users:[]}  },  componentDidMount:function(){    var _this = this;    $.get(“http://localhost:8080/users?act=get”,function (data){      console.log(data);      _this.setState({        users:data      });    });  },  render: function () {    var users = this.state.users;    console.log(users);    return <table>    {      users.map(function (user,key){      return <tr key={key}><td>{user.firstName}</td><td>{user.lastName}</td></tr>    })    }    </table>  }});ReactDOM.render(<Input/>,document.getElementById(“test”));

The above is the React-related knowledge introduced by the editor. I hope it will help you. If you have any questions, please leave a message. The editor will reply to you in time. Thank you very much for your support for the help House website!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.