1
votes

Here's a bit of code for the React component that uses Mobx to manage state.But different ways of using it lead to completely different results.

App.js

import React from "react";
import "./styles.css";
import { observer } from "mobx-react";
import store from "./store";

const Span = () => {
  return <span>{store.count}</span>;
};

const app = function () {
  return (
    <div className="App">
      {/* section 1 */}
      <Span />

      {/* section 2 */}
      {/* <span>{store.count}</span> */}

      <button onClick={() => store.setCount(store.count + 1)}>Click</button>
    </div>
  );
};

export default observer(app);

store.js

import { observable, action } from "mobx";

class Store {
  @observable count = 0;

  @action setCount(count) {
    this.count = count;
  }
}

export default new Store();

Using section 1, clicking on the button does not refresh the view, but using Section 2 does.

codesandbox

1、I want to know the difference between using these two methods?

2、If I stick with section 1, how do I change the code?

1

1 Answers

3
votes

just wrap the observer on your Span Component.

const Span = observer(() => {
  return <span>{store.count}</span>;
});

Span doesn't observe your store, so it didn't know what changed.