Change detection with react

后端 未结 2 1422
别跟我提以往
别跟我提以往 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 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(
          
    {this.state.name}
    ) } }

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

提交回复
热议问题