Change detection with react

后端 未结 2 1423
别跟我提以往
别跟我提以往 2021-02-06 02:08

I\'m studying change detection mechanism and I\'m having some troubles with reactjs case.

When props are changed in a react component, this component is \"rerendered\" (

相关标签:
2条回答
  • 2021-02-06 02:46

    You said

    when something happens, react browse its internal virtual DOM

    that something is when a new prop is being passed or if a state gets changed. Are you asking for how react internally knows when either of these happen?

    0 讨论(0)
  • 2021-02-06 03:08

    Try to imagine there are 2 things here:

    • the component (COMPONENT) itself, and
    • things outside of the component (OUTSIDE):

    A change inside the COMPONENT

    You need to call this.setState(), this would update the state inside the current component, and subsequently trigger an update (automatically call render()) of this component

    A change from the OUTSIDE

    This would trigger the props/newProps of this COMPONENT to be updated, and subsequently your component is updated by calling this.setState() inside the component (componentWillReceiveProps is a lifecycle method from React)

    class MyComponent extends React.Component {
      // initially how the state is set to MyComponent
      constructor(props) {
        super(props);
        this.state = {name: this.props.name};
      }
    
      // own method to be called inside MyComponent
      updateName(e) {
        const newName = e.target.value;
        if (this.state.name !== newName) {
          this.setState({name:newName});
        }
      }
    
      // changes from the outside
      componentWillReceiveProps(nextProps) {
        const newName = nextProps.name;
        if (this.state.name !== newName) {
          this.setState({name:newName});
        }
      }
    
      render() {
        return(
          <div>
            {this.state.name}
            <input type="text" 
                   onChange={this.updateName.bind(this)} 
                   value={this.state.name} />
          </div>
        )
      }
    }
    

    It's worth pointing out that this.setState() would automatically trigger render(), while this.state.name = 'Bob' wouldn't trigger render().

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