What is workflow of the React

前端 未结 2 1500
日久生厌
日久生厌 2021-01-31 03:16

The code below is from React, which updates the DOM dynamically. I used the tutorial by Facebook react but did not understand the whole code, i.e which part of the

相关标签:
2条回答
  • 2021-01-31 03:56

    You can find more general explanation on React official page. Generally the react lifecycle can be described by the following stages (which can repeat multiple times once the components is created):

    Initializing values (only once):

        constructor(){ ... }
    

    Mounting, if you need to add something after initial rendering (only once):

        componentDidMount(){...}
    

    Re-rendering functions, variables and components

        myArrowFunction = () => {
          ...
          this.setState({...})
          ...  
        }   
    

    Updating:

        componentDidUpdate()}{...}
        shouldComponentUpdate(){...}
    

    Unmounting:

        componentWillUnmount(){...}
    

    Rendering happens here

        render(){...}
    
    0 讨论(0)
  • 2021-01-31 04:00

    Thanks, that's a very good question. Here's a rough overview of what is happening behind the scenes:

    Initialization

    It all starts with this line:

    React.renderComponent(<TodoApp />, mountNode);
    

    This instantiate the TodoApp component which calls:

    TodoApp::getInitialState()
    

    then, it renders the TodoApp component

    TodoApp::render()
    

    which in turns instantiate a TodoList

    TodoList::render()
    

    At this point, we have everything we need in order to render the initial markup

    <div>
      <h3>TODO</h3>
      <ul></ul> <!-- <TodoList> -->
      <form>
        <input value="" />
        <button>Add #1</button>
      </form>
    </div>
    

    It is stringified and added inside of mountNode via innerHTML

    OnChange

    Then let's say you're going to enter some text in the input, then

    TodoApp::onChange
    

    is going to be called, which is going to call

    TodoApp::setState
    

    and in turn will call

    TodoApp::render
    

    again and generate the updated DOM

    <div>
      <h3>TODO</h3>
      <ul></ul> <!-- <TodoList> -->
      <form>
        <input value="sometext" />
        <button>Add #1</button>
      </form>
    </div>
    

    What's happening at this point is that React is going to do a diff between the previous DOM and the current one.

        <div>
          <input
    -       value=""
    +       value="sometext"
    

    Only the value of the input changed, so React is going to just update this particular attribute in the real DOM.

    0 讨论(0)
提交回复
热议问题