天落枫
2021-07-18 17:01
采纳率: 100%
浏览 793

react hook组件使用mobx,mobx状态更新但react页面不刷新!

我想使用函数组件来重构类组件,在函数组件中使用了hook,同时发现改变mobx状态,页面不刷新,只有改变hook的state页面才更新

store.js

import { observable, action } from "mobx";

class CountStore {
  @observable a = 1;
  @observable b = 2;

  @action
  add = () => {
    this.a++;
  };
  @action
  add2 = () => {
    this.b++;
  };
}

const countStore = new CountStore();
export default countStore;

App.js

import { observer } from "mobx-react";

import React, { useEffect, useState } from "react";

const App = (props) => {
  const [x, setX] = useState(0);

  useEffect(() => {
    console.log(props);
  });

  return (
    <div className="App">
      <div>x:{x}</div>
      <div>{props.store.a}</div>
      <div>{props.store.b}</div>
      <button onClick={setX.bind(null, x + 1)}>set x</button>
      <button onClick={props.store.add}>add按钮1</button>
      <button onClick={props.store.add2}>add2按钮2</button>
      <br />
    </div>
  );
};

export default observer((props) => {
  return <App store={props.store} />;
});

index.js

// 省略一些
ReactDOM.render(<App store={countStore} />, rootElement);

如果使用:export default observer(App);导出,则会报错:Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

实在是不知道怎么改了,请大 佬帮 忙看 看,十分 感 谢

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

2条回答 默认 最新

相关推荐 更多相似问题