11.--state Status of React series

Source: Internet
Author: User
Tags comments constructor diff json

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

PS: Reprint please indicate the source
Author: tigerchain
Address: http://www.jianshu.com/p/44a787904d9b
This article originates from Tigerchain Pinterest

React Tutorial Series

Introduction to Tutorials

1. Reading objects

This tutorial is suitable for beginners to read, the veteran directly skipped

2. Tutorial Difficulty

Primary

Note: This article uses ES6 's writing, does not have the special explanation to use the Es6+yarn+webpack to write the demo 1, what is the state

We all say that react is a state machine, the embodiment of what is, is reflected in the State, through the interaction with the user to achieve a different status, and then to render the UI, so that the user's data and interface consistency. State is the private property of the component.

In react, updating the state of the component will result in a re-rendering of the user interface (no manipulation of the DOM), in a nutshell, the user's interface will change as the status changes.

Ps:state can only be initialized in this component, and state can only be modified and imitated by this component, cannot be externally imitated and modified, so it can also be said that state is private to the component. 2. How to use state

1. Initialize State

For the use of State, in ES5 and ES6 in the use is not the same, we take ES6 as an example, in the component's construction method as follows, set a default state property.

Constructor (props) {
   super (props);
   this.state={
      key:value,
      ...
   }
}

2. Update state

Update state calls the following methods

This.setstate ({
     key:value
 });

Don't do this, This.state.key = XXX; This will not re-render the interface

Note: SetState () is asynchronous, that is, after you call SetState (), React is ready to update, and the intermediate calculation may have a certain delay.

PS: If the SetState () method is called, the render () method is called, which is what is said earlier, and the user's interface will change as the state changes.

3. Call the diff algorithm

This step is based on a 2 step, and SetState () will trigger the diff algorithm to eventually determine whether to update. 3, what kind of components should have state

It should be said that most of the components are based on props to get the data and render, but the user inputs, requests the server, Operation of the database, etc. the state is required. The official recommendation is to build stateless components as much as possible to improve performance and reduce rendering times by building a few stateless components on which to build a stateful and user and service interaction, and then pass the props to the stateless component.

Use state to pay attention to three things 1, do not directly modify the state

Counter example  Please do not do this
this.state.comment = ' Hello ';

The correct approach is to use the SetState () method

Correct procedure
this.setstate ({
    Comment: ' Hello ',
})
2. Status update is asynchronous

In the official words, this.props and this.state may be asynchronous when updated, so you should not rely on their values to calculate the next state.

Here is an example of the error

Counter Example
this.setstate ({
  counter:this.state.counter + this.props.increment,
});

The right example

The correct example
this.setstate ((prevstate, props) = ({
  counter:prevState.counter + props.increment
})
3. The state update is a merged

When you call SetState (), React merges the objects you provide into the current state.

For example, your state may contain several independent variables.

Constructor (props) {
    super (props);
    This.state = {
      posts: [],
      comments: []
    };
  }

Then you can update them independently by calling SetState ()

Componentdidmount () {
    fetchposts (). Then (response = {
      This.setstate ({
        posts:response.posts
      });
    }) ;

    Fetchcomments (). Then (response = {
      This.setstate ({
        comments:response.comments
      });
    });
  

This merge is a shallow merge, so This.setstate ({comments}) will make the this.state.posts complete, but will completely replace the this.state.comments. 4. Start the Code

Say 1000, Tao 10,000, are in the theoretical level, below we start from 0 to write a simple demo to experience state. Use Webpack+yarn below to write a demo.

In the MAC environment, win under the basic difference is not too much

1. Create a new state directory under the specified directory (command line operation)

mkdir State

2. Initialize the project with yarn (command line operation)

CD State
yarn Init

In the above steps all the way to enter

3. Install some dependencies (command line operation)

Yarn Add react react-dom webpack webpack-dev-server babel-core babel-loader babel-preset-react bable-preset-es2015 babel-preset-stage-0--dev

Then enter, wait for the installation to depend on, if there is no problem can see the following results in the Package.json (red box)

The above indicates that your reliance on the installation is successful.

4. Create a new. BABELRC in the State root directory and enter the following

{"
  presets": ["React", "es2015", "stage-0"]
}

5. Create a new app and public folder in the State directory

6. Create a new index.html in public and enter the following content

<! DOCTYPE html>

7. Create Main.js and State.js in the app directory respectively

# main.js

import React from ' React ';
Import reactdom from ' React-dom ';

Import state from './state.js ';
Reactdom.render (
  <state/>,
  document.getElementById (' container ')
);
# state.js
Import React, {Component, proptypes} from ' React ';

/**
 * Use ES6 syntax to define a state component *
/export default class state extends Component {

  Constructor (props) {
    Super (props);
    This.state = {//Initialize state
      countnum:0,
    };
  }

  /**
   * Click event method countnum+1
   *
  /_handlerevent () {
    this.setstate ({
      countnum: This.state.countnum+1,
    })
  }
  render () {
    return (<div>
      {this._renderview ()}
    } </div>);
  }
  /**
   * Renders a button component */
  _renderview () {
    return (
      <div>
        <button onclick={this. _handlerevent.bind (This)}> click {This.state.countnum} times </button>
      </div>
    );
  }
}

8. Create a new webpack.config.js in the state root directory and enter the following, it is not clear to see webpack this section: http://www.jianshu.com/p/732c4d501668

Module.exports = {
  entry:__dirname+ '/app/main.js ',
  output:{
    path:__dirname+ '/public ',
    filename: ' Bundle.js '
  },
  devserver:{
     contentbase: "./public",//directory where the local server loads the page
     historyapifallback:true,// Do not jump
     inline:true//real-time Refresh
   },
  module:{
    loaders:[
    //babel configuration
    {
      test:/\.js$/,
      Exclude:/node_modules/,
      loader: ' Babel-loader '
    }
  ]
  }
}

9, add script in Package.json (this is not necessary, but can be easily called)

The blue part of the figure is the script we added, namely:

"Scripts": {
    "start": "Webpack-dev-server--progress--port 8888"
 }

10, run yarn start directly on the command line if there is no problem, we enter localhost:8888 on the browser, we will see the following results

We have completed a simple state example, from this example we can see that whenever I click on the button, the status of the component will change, the count will be added 1, but when we call the SetState () method in the end there is no refresh interface. Let's test it again.

11, then the above example we continue to modify State.js

We can see from the diagram that we just added a modern warfare method based on the original, used to test the number of calls to the Render method, and then save and look at the results (open Chrome's Debug bar)

From the diagram we can see clearly, how many times we clicked, the Render method called the number of times, so that when the SetState () method is called to re-render the interface

So far, we have a general understanding of state. Let's say an example of a stateless component. 5. Non-stateful components 1. What is a stateless component

A stateless component is a component without a state, as the name implies. We mentioned the stateless component, the official recommendation is to try to make the component stateless, but there must be a place to state, the general practice is to combine the components of the stateless, the host component has a state setting (in general, That is, when the parent component updates the child components, but sometimes it turns out

Next we build a stateless component and then pass the state through props to the stateless component to update the UI by interacting with the user (click), so it might be a bit of a detour to see the following figure to intuitively understand

The image above is a pseudo-code for this process, which is well understood. 2, we through a demo to intuitively feel

1. Then the above example, we continue to create passstateofprops.js and Stateless.js separately in the app

# passstateofprops.js This component can be used as a stateful parent component import React, {Component, proptypes} from ' React ';

Import stateless from './stateless.js ';
    /** * Props to pass state to update component's Purpose */export default class Passstateofprops extends Component {constructor (props) {
    Super (props);
   This.state = {//Initialize state list:[' 111 ', ' 222 ', ' 333 ']}}/** * Render interface */Render () {return (<div> {This._renderbutton ()} {/*) passes the state through props to the stateless component stateless */} & Lt
  Stateless datas={this.state.list}/> </div>); }/** * Renders a button */_renderbutton () {return (<div> <button onclick={this._handlerevent.b
  IND (this)}> change values </button> </div>);
  }/** * Click events */_handlerevent () {this.setstate ({list:[' 444 ', ' 555 ', ' 666 ')}); }
}
#  Stateless.js  defines a stateless component

import React, {Component, proptypes} from ' React ';

/**
 * Defines a stateless component *
/export default class stateless extends Component {

  render () {
    return (<div >
      <ul>
        {
          this.props.datas.map (function (data) {
            return (
              <li>{data}</li >
            )}
          )
        }
      </ul>

    </div>);
}}

2. Modify the code in Main.js

The yellow part is the part we modified.

3. View Results

We see that passing state to stateless components through props is running successfully, so we'll develop it later in the project and use the stateless components as much as possible, and take this idea and habit from now on. The address of this demo

Https://github.com/githubchen001/react-lesson/tree/master/lesson02/09-state

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.