React Mobx - the component is not updated after changing the store

Using Mobx, after updating the repository (i.e. by clicking the button), the component will not be rendered again. I installed mobx devtools, which shows nothing after the initial boot, and there is no error in the console. Any ideas what I did wrong?

Store.js:

import { observable } from 'mobx'; class Store { @observable me; constructor() { this.me = 'hello'; } change_me(){ this.me = 'test 1234'; } } export default Store; 

layout.js:

 import React from "react"; import { observer } from 'mobx-react'; @observer export default class Layout extends React.Component{ render(){ return( <div> <h1>{this.props.store.me}</h1> <button onClick={this.on_change}>Change</button> </div> ) } on_change = () => { this.props.store.change_me(); } } 

index.js:

 import React from "react"; import ReactDOM from "react-dom"; import Layout from "./components/Layout"; import Store from "./Store"; import DevTools, { configureDevtool } from 'mobx-react-devtools'; // Any configurations are optional configureDevtool({ // Turn on logging changes button programmatically: logEnabled: true, // Turn off displaying conponents' updates button programmatically: updatesEnabled: false, // Log only changes of type `reaction` // (only affects top-level messages in console, not inside groups) logFilter: change => change.type === 'reaction', }); const app = document.getElementById('app'); const store = new Store(); ReactDOM.render( <div> <Layout store={store} /> <DevTools /> </div> , app); 
+5
source share
3 answers

I would start by adding @action to your change_me () function. From what I understand, this is not always completely necessary, but several times I encountered such problems in my own code when I forgot to add it.

Also, submit your .babelrc as suggested by @mweststrate, as it will help others verify that the plugins are loading correctly.

+2
source

Watch the binding of this context.

 <button onClick={this.on_change}>Change</button> 

this link will not belong to the class, so probably when you actually click it will say something like strings without undefined links. The change:

  <button onClick={this.on_change.bind(this)}>Change</button> 

must fix it. Or even better, bind the context in the constructor so that it does not bind on each render

  constructor(props) { super(props) this.on_change = this.on_change.bind(this) } 

then you can return to

0
source

My guess would be to have uninitialized @observable. This is very controversial, but Babylon does not cope with these problems. Even adding @observable me = undefined can help (see Generated js code when you assign something there. Usually I completely remove the constructor and put initialization in the declaration (ie @observable me = "hello" there is no constructor). p>

0
source

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


All Articles