Giter Club home page Giter Club logo

odd's People

Contributors

rayjune avatar

Watchers

 avatar

odd's Issues

React lifecycle methods

This one fires when the component first gets mounted to the DOM that is known as:
componentDidMout

This is something that we only have access to in our class based components.
There is no way to manage lifecycle for stateless functional components.
So this is actually another reason why stateless functional components are so fast

demo:

class AddOption extends React.Component {
  constructor(props) {
    super(props);
    this.handleAddOption = this.handleAddOption.bind(this);
    this.state = {
      error: undefined
    };
  }
  componentDidMount() {
    console.log('mount');
  }
  componentDidUpdate(prevProps, prevState) {
    console.log('update');
  }
  componentWillUnmount() {
    // barely use, but it's important to know it exists
    console.log('componentWillUnmount');
  }
  handleAddOption(e) {
    e.preventDefault();
    console.log('just a demo :)');
  }
  render() {
    return (
      <div>
        {this.state.error && <p>{this.state.error}</p>}
        <form onSubmit={this.handleAddOption}>
          <input type="text" name="option" placeholder="存放一个小心愿把:)"/>
          <button>添加</button>
        </form>
      </div>
    );
  }
}

google: react lifecycle

https://reactjs.org/docs/state-and-lifecycle.html

The stateless functional component: when use it

The stateless functional component suitable for simple presentational components.(especially without state)

They are faster than our class based components.
So when we can we should be using them there faster because they don't come with all of the overhead, and baggage of being a class and having to extend to react component(for example: state)

demo:

const User1 = () => {
  return (
    <div>
      <p>Name: {this.props.name}</p>
      {/*stateless functional components do not have access to `this` obviously are arrow functions do not either*/}
    </div>
  );
};

// so:

const User2 = (props) => {
  return (
    <div>
      <p>Name: {props.name}</p>
    </div>
  );
};

ReactDOM.render(<User2 name={'RayJune'} />, document.getElementById('app'));

Props vs State: React Component's properties battle

Similarities:

  • are objects
  • can be used when rendering
  • changes cause re-renders(props's change from parent, state's change by itself)

Differences:

props

  • props from above

Whether it's a parent component or just some JSX that gets passed into react-done render.

  • can't be changed by the component itself

We know that data props they flow in one direction
That allows us to pass things between components so the parents could pass some data

parentComponent -> childComponent

state

  • state is defined in the component itself
  • can be changed by the component itself

Summary

父子组件传递信息 -> props
自身组件控制 data change & re-render -> state

&& ||

The || operator takes two arguments.

  • If the first argument is a "truthy" value, it returns the first argument;
  • otherwise, it returns the second.

It also short-circuits; that is, if the first argument is truthy it does not evaluate the second.

about &&

  • If first value is false, it is not going to actually use that,
  • If the second value is truthy, that is going to get used.
render: true && <p>{app.subtitle}</p> => <p>{app.subtitle}</p>

First letter uppercase in React Compenent

React force React component's first letter must be uppercase.

It's what allows React to figure out if the thing we're trying to render is a component or an HTML element

For example, a React component called Header:

class Header extends React.Component {
  // React.Component requie 1 method to be defined: render
  render() {
    return (
      <div>
        <h1>文章本天成,妙手偶得之</h1>
        <h2>代码即诗歌</h2>
      </div>
    );
  }
}

ReactDOM.render:

const rayjune = (
  <div>
    <Header /> 
    <Action />
    // react force component's first letter must be uppercase
    // It's what allows react to figure out if the thing we're trying to render is a component or an HTML element
    <header /> 
  </div>
);

ReactDOM.render(rayjune, document.getElementById('app'));

and compiled code:

var rayjune = React.createElement(
  'div',
  null,
  React.createElement(Header, null),
  React.createElement(Action, null),
  '// react force component\'s first letter must be uppercase // It\'s what allows react to figure out if the thing we\'re trying to render is a component or an HTML element',
  React.createElement('header', null)
);

ReactDOM.render(rayjune, document.getElementById('app'));

How React Component state is going

React component state allows our components to manage some data.

So just think about an object with various key-value pairs , and when that data changes the component will automatically re-render to reflect those changes.

All we have to do is manipulate the data and the component is going to take care of re-rendering itself.

  1. Setup default state object
  2. Component rendered with default state values
  3. Change state based on event
  4. Component re-rendered using new states
  5. start at 3 again

this.setState can handle this situation:

demo MagicalCounter:

class MagicalCounter extends React.Component {
  constructor(props) {
    super(props);
    this.handleAddOne = this.handleAddOne.bind(this);
    this.state = {
      count: 0
    };
  }
  handleAddOne() {
    // this.state.count += 1; can't re-render automatically
    this.setState((prevState) => {
      return {
        count: prevState.count + 1
      };
    });
    console.log(this.state.count);
  }
  render() {
    return (
      <div>
        <h1>Magical Counter:{this.state.count}</h1>
        <button onClick={this.handleAddOne}>+1</button>
      </div>
    )
  }
}

ReactDOM.render(<MagicalCounter />, document.getElementById('app'));

Arrow functions => no bound this anymore

ES5 solution: use that to bind this

const user = {
  name: 'rayjune',
  cities: ['Hangzhou', 'Beijing', 'Shanghai'],
  printPlacesLived: function () {
    const that = this;
    return this.cities.map(function (city) {
      that.name + ' has lived in ' + city
    });
  }
};
console.log(user.printPlacesLived());

ES6 arrow function:

But this can't work,because arrow functions don't bind this:

const user = {
  name: 'rayjune',
  cities: ['Hangzhou', 'Beijing', 'Shanghai'],
  printPlacesLived: () => {
    return this.cities.map((city) => this.name + ' has lived in ' + city);
  }
};
console.log(user.printPlacesLived());

ES5(just more concise writing style) + ES6, :

This demo work because arrow functions don't bind this:

// this keyword - no longer bound

const user = {
  name: 'rayjune',
  cities: ['Hangzhou', 'Beijing', 'Shanghai'],
  printPlacesLived () {
    return this.cities.map((city) => this.name + ' has lived in ' + city);
  }
};
console.log(user.printPlacesLived());

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.