state

The basic definition

State is the state (data) inside the component. It cannot be modified directly. SetState must be used to change the state of the value, so as to achieve the function of updating the data inside the component.

props

The basic definition

Props is a way of passing between components. Of course, props can also pass state. React data flows from parent to child components because it is top-down. The this.props property inside the component is read-only and cannot be modified.

Code sample

// Parent component import stateJj from'./stateJj.js'; Class stateJjFather extends React.Component {constructor(props) {super(props); // Set the default value of state and only set this. State = {mes:'Information for child Components', obj: {}, arr: []}} fun(e) {}render() {
        const {mes, obj, arr} = this.state;
        return<div> // Do not write the arrow function this pointing to an error can also be usedbindThis <stateJj name={'Information for child Components'} name1={mes} fun={(e) => this.fun(e)} obj={obj} arr={arr} /> </div> ); }} // Class stateJj extends React.Component {constructor(props) {super(props); this.props; / / pass the value of the parent component in the / / set the default state. This state = {text: props. The initialValue | |'placeholder'}; // ES6 classes must manually bind this.handlechange = this.handlechange.bind (this); } handleChange(event) { this.setState({ text: event.target.value }); }render() {
        return( <div> {mes} </div> ); PropTypes = {optionalArray: propTypes. Array, optionalBool: propTypes. Bool, optionalFunc: PropTypes.func, optionalNumber: PropTypes.number, optionalObject: PropTypes.object, optionalString: PropTypes. String, optionalSymbol: PropTypes. Symbol, // All variable types that can be declared currently}; // set the defaultProps value stateJj. DefaultProps = {};Copy the code

The characteristics of the props

  1. read-only

Props is often used for rendering components and initialization states. After a component is instantiated, its props are read-only and immutable. If the props can be changed during rendering, this will result in the appearance of the component becoming unpredictable. You can only pass new props into a component by re-rendering it from the parent component.

  1. invariance

The child component can only be re-rendered by an external component actively passing in new props, otherwise the props and presentation of the child component will not change.

Use setState to change the value of state

Unlike props, state can be changed. However, you cannot change state directly with this.state=. Instead, you need to change state with this.setstate ().

Note: State can only be set to default values in constructor

SetState Basic usage

React updates the state of the component’s data and re-invokes the render method, which rerenders the component.

Apihelper.shipinfo ({shipName: value}).then(res => {let datas = res.data;
        this.setState({
            dataList: datas,
        })
    }).catch(err => {
        this.setState({
            isLoading: false,ue
        });
    })
Copy the code

Considerations for using setState

  1. When we call this function, react. js updates the component’s state and re-invokes the Render method, which then renders the latest content to the page
  2. React.js does not change state immediately. Instead, the object is placed in an update queue, and the new state is later extracted from the queue and merged into state, which then triggers the component update. In other words, the update of setState is asynchronous

Update state instantly:

  1. Use the second argument of setState
    setState({
       mes: '123' 
    }, function() { console.log(this.state.mes); });Copy the code
  1. Call setState with methods not detected by React
    setTimeOut(function() {
        setState({ mes: 123 }) }, 500); React doesn't monitor methods in timers and delayers. // Use native events when calling eventscomponentDidMount() {
      document.querySelector('#btn-raw').addEventListener('click', this.onClick);
    }
    onClick() {
      this.setState({count: this.state.count + 1});
      console.log('# this.state', this.state); // Prints the current value} //......render() {
      console.log('#enter render');
      return (
        <div>
          <div>{this.state.count}
            <button id="btn-raw">Increment Raw</button>
          </div>
        </div>
      )
    }
    
Copy the code

conclusion

  1. Props defines the external interface, and state records the internal state
  2. The assignment of props is to use the component in the external world, and the assignment of state is to use the component inside
  3. The component should not change the value of props, and state is there for the component to do that
  4. State can only be set by default in constructor
  5. SetState Changes the value of state asynchronously