简体   繁体   中英

ReactJS & MobX: TypeError: … is not a function - but it is?

SidenavStore.js - defines if the Sidenav should be visible or not, default true:

const SidenavStore = types
  .model('SidenavStore', {
    isSidenavVisible: types.optional(types.boolean, true),
  })
  .actions(self => ({    
    hideSidenav: () => { self.isSidenavVisible = false; },
    showSidenav: () => { self.isSidenavVisible = true; },
  }));

export default SidenavStore;

The ErrorPage makes use of the SidenavStore to determine whether or not to show the Sidenav.

import sidenavStore from '../../../stores/SidenavStore';

class ErrorPage extends React.Component {
  componentDidMount() {
    sidenavStore.hideSidenav();
  }

  componentWillUnmount() {
    sidenavStore.showSidenav();
  }

  render() {
    return (
      <div>
        <h1>My Content Here</h1>
      </div>
    );
  }
}

And in App.jsx , the applicable code:

const sidebarStore = SidebarStore.create();

const App = () => (
  <BrowserRouter>
    <Provider sidebarStore={SidebarStore}>
      <Main>
        {code here}
      </Main>
    </Provider>
  </BrowserRouter>
);

export default App;

So my question is this:

In the browser, I'm getting the error TypeError: _stores_SidenavStore__WEBPACK_IMPORTED_MODULE_8__.default.hideSidenav is not a function . Yet, you can see that both hideSidenav and showSidenav exist in SidenavStore.js.

What am I referencing or doing wrong? Any guidance would be much appreciated.

You are currently importing the model and trying to use that. You instead want to get the instance from your Provider with inject and use that from the props.

import { observer, inject } from "mobx-react";

class ErrorPage extends React.Component {
  componentDidMount() {
    this.props.sidenavStore.hideSidenav();
  }

  componentWillUnmount() {
    this.props.sidenavStore.showSidenav();
  }

  render() {
    return (
      <div>
        <h1>My Content Here</h1>
      </div>
    );
  }
}

export default inject("sidebarStore")(observer(ErrorPage));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM