How to connect state to props with mobx.js @observer when use ES6 class?

前端 未结 4 1746
逝去的感伤
逝去的感伤 2021-01-30 14:54

Let\'s take a class like this in an app with React and React Router.

@observer class Module1 extends React.Component {

  constructor (props) {
    super(props);         


        
4条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-30 15:28

    mobx-react offers a (experimental - at the time of writing this) Provider (component) and inject (higher order component) to pass properties to the component hierarchy below.

    From above you can use the Provider component to pass all relevant information. Under the hood React context is used.

    import { Provider } from 'mobx-react';
    ...
    import oneStore from './stores/oneStore';
    import anotherStore from './stores/anotherStore';
    
    const stores = { oneStore, anotherStore };
    
    ReactDOM.render(
      
        
          
            
          
        
      ,
      document.getElementById('app')
    );
    

    In SomeComponent you can retrieve the passed properties by using the inject HOC:

    import { observer, inject } from 'mobx-react';
    ...
    
    const SomeComponent = inject('oneStore', 'anotherStore')(observer(({ oneStore, anotherStore }) => {
      return 
    {oneStore.someProp}{anotherStore.someOtherProp}
    ; })) export default SomeComponent;

    [Disclaimer: I wrote about it in MobX React: Simplified State Management in React and you can see a minimal boilerplate application which consumes the SoundCloud API.]

提交回复
热议问题