4

I am tring to use the Mobx to manage my react-project's state,but I cannot get the props from the Provider by mobx-react.

This is my root element(I delete the router to simplify the question):

import React from "react";
import ReactDOM from "react-dom";
import {Router, Route, hashHistory} from "react-router";
import {Provider} from "mobx-react";

import store from "../store";
import App from "./app";

ReactDOM.render((
    <Provider store={store}>
       <App/>
    </Provider>),
  document.getElementById("content"));

and this is my childNode:

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

@inject("store") @observer
export default class App extends Component {
  constructor(props) {
    super(props);

    console.log(this.props.store);
  }

  render() {
    return (
      <div>
        ab
      </div>
    )
  }
}

App.propTypes = {
  store: PropTypes.observableObject
};

But when I log the store,the result is undefined, and I don't know why I cannot get the store.

From the chrome devtools, I find the Provider has the store but App cannot get store,I am very confused.

My store is bellow:

import {observable} from "mobx";
class Store {
  @observable count;

  constructor() {
    this.count = 1;
  }

  addCount() {
    this.count += 1;
  }

  decreaseCount() {
    this.count -= 1;
  }
}

let store = new Store();

export default store;
Yingch Xue
  • 3,013
  • 2
  • 9
  • 11
  • You have never assigned to App component your Store. you are passing to Route the component like this: `component={App}`. I think you should assig to App the Store first – Facundo La Rocca Jan 09 '17 at 17:57
  • Have you tried passing a function as the argument to your `inject` decorator and seeing what stores are available? Something like `@inject((stores) => { console.log(Object.keys(stores)); return { store: stores.store }; })` – Paul S Jan 09 '17 at 19:06
  • I use the chrome devtools and ensure the store is available. – Yingch Xue Jan 09 '17 at 19:12
  • the function isn't invoked, maybe I think the inject things don't be call @Paul S – Yingch Xue Jan 09 '17 at 19:24
  • It certainly seems like `inject` isn't being called for some reason. Have you seen this example project? https://github.com/contacts-mvc/mobx-react-typescript Your code appears to be similar, so I'm not sure what is going on. Perhaps you could try the non-decorator method? `export default inject(...)(observer(App))` – Paul S Jan 09 '17 at 19:35
  • a THX! I find is that the decorator is not useful, and I use non-decorator method.thank you very much! – Yingch Xue Jan 09 '17 at 19:46
  • It seems like you edited your question with the solution since the code works for me: https://stackblitz.com/edit/react-c4mbg3 – Christopher Chiche Jan 30 '18 at 13:48

0 Answers0