usage

MobX provides a Mobx-React package to help developers easily use MobX with React. Observer / @Observer comes from this package. Here are two other commonly used apis in Mobx-React.

  • The Provider:ProviderReact is a React component that uses the React context mechanism to pass the required state to its child components. It functions as provided by React-ReduxProviderThe components are the same.
  • Inject:injectIs a higher-order component, which is the same asProviderUsed in combination fromProviderSelect the required data from the supplied state and pass it to the target component as props.

There are two common modes:

inject("store1"."store2")(observer(MyComponent));
Copy the code
@inject("store1"."store2");
@observer MyComponent;
Copy the code

A simple example:

import React, { Component } from 'react'
import ReactDOM from 'react-dom'
import { observer, inject, Provider } from 'mobx-react'
import { observable } from 'mobx'

@inject('store')
@observer
// Inject the Store object from the context into the props of the component
class App extends Component {
  render () {
    const { store } = this.props
    return (
      <div>
        <ul>
          {store.map(todo => (
            <TodoView todo={todo} key={todo.id} />
          ))}
        </ul>
      </div>)}}const TodoView = observer(({ todo }) = > {
  return <li>{todo.title}</li>
})

// Construct the store and its initial data
const todos = observable([])
todos.push({ id: 1.title: 'Task1' })
todos.push({ id: 2.title: 'Task2' })

ReactDOM.render(
  {/* Provider injects store objects into context */}
  <Provider store={todos}>
    <App />      
  </Provider>, document.getElementById("root"));Copy the code

The order of @inject and @observer

There is an order problem in the writing of @inject and @observer. Write in an incorrect order will invalidate Inject.

// index.tsx
const Main = (props: RouteConfigComponentProps<any>) = > {
  return({/* Provider injects store objects into context */} <Provider {... stores}><Main {. props} / >
    </Provider>
  );
};
Copy the code

Scene 1:

@observer
@inject('homePageStore')
class Main extends React.Component<{}, {}> { ... }
Copy the code



As you can see,homePageStoreIs still incontextThe injection is not taken outprops.


Scene two:

@inject('homePageStore')
@observer
class Main extends React.Component<{}, {} > {}Copy the code



Inject correctly intoprops.