MobX Why should I use `observer` when I could use` inject` when entering data into the React component

The MobX documentation suggests that I should use observerfor all of my components. However, by using injection, I get finer-grained control over which data leads to the re-rendering of my components.

I understand that with a observerchange in all available observables in the last render, it will cause re-visualization, even if the observable is embedded deep in the data store, but injectonly re-displays when the observable data is available when the nozzle function changes.

For instance:

class Store{
  @observable data = {
    nestedData: {
      deepData: 'my_data'
    }
  }
}

const store = new Store();

... Assume the store is injected using <Provider /> component

// This will cause re-render when the data object changes
// for example: store.data = { new_data: 'new_data' }
@inject(stores => {
  return { data: stores.dataStore.data }; 
})
class MyComponent extends Component {  }

// This will re-render on change of the data object, but also
// on change of nestedData and deepData properties
@inject(stores => {
  return { data: stores.dataStore.data }; 
})
@observer
class MyComponent extends Component {  }

Can anyone confirm my understanding of this?

-, inject, . , , , .

/

+2
1

, . :

@observer , render, .

, @observable, render, prop :

class Store{
  @observable data = {
    nestedData: {
      // changes to `deepData` would theoretically re-render any observer
      deepData: 'my_data' 
    }
  }
}

, ,

!

observable, ...


, @inject, ( props) , Provider.

:

@inject('title')
class MyComponent extends React.Component {
    render() {
        return (<div>{this.props.title}</div>);
    }
}

const Container = () => (
    <Provider title="This value is passed as a prop using `inject`">
        <MyComponent />
    </Provider>
);

, .

!

inject , prop .


shouldComponentUpdate() props - observer be , shouldComponentUpdate.

-, , .

... , .

:

class Store{
    @observable data = {
        nestedData: {}
    };

    constructor() {
        this.data.nestedData.deepData = 'my_data';
    }
}

... deepData (.. ), , data . .

:

class Person {
    @observable name = 'John Doe';
}

class Store{
    @observable data = null;

    constructor() {
        this.data = new Person();
    }
}

, Store ( Store.data, Person.

+1

Source: https://habr.com/ru/post/1692943/


All Articles