我想使用函数组件来重构类组件,在函数组件中使用了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:
实在是不知道怎么改了,请大 佬帮 忙看 看,十分 感 谢