我目前正在编写一个 React 应用程序,它应该能够在任何可观察到的值发生变化时重新渲染组件。问题是我无法得到email
如果发生变化则重新渲染。
store.ts
export class ExampleStore {
@observable email = 'hello';
@action setEmail(email: string) {
this.email = email;
}
}
索引.tsx
const stores = {
exampleStore
};
ReactDOM.render(
<Provider {...stores}>
<App />
</Provider>,
document.querySelector('#root')
);
App.tsx
interface Props {
exampleStore?: ExampleStore;
}
@inject('exampleStore')
@observer
export class App extends React.Component<Props, {}> {
componentDidMount() {
setInterval(() => {
this.props.exampleStore!.setEmail(Math.random() * 10 + '');
}, 2500);
}
render() {
const { email } = this.props.exampleStore!;
return <div>{email}</div>;
}
}
我见过很多例子使用useContext
钩子,但我必须使用类组件。我不确定为什么这不会再次调用渲染函数。我有mobx
and mobx-react
安装。
你在使用 MobX 6 吗?
Decorator API 发生了一些变化,现在你需要使用makeObservable
构造函数内的方法实现与以前相同的功能:
class ExampleStore {
@observable email = "hello";
constructor() {
makeObservable(this);
}
@action setEmail(email) {
this.email = email;
}
}
尽管有新的东西可能会让你完全放弃装饰器,makeAutoObservable
:
class ExampleStore {
email = "hello2";
constructor() {
// Don't need decorators now, just this call
makeAutoObservable(this);
}
setEmail(email) {
this.email = email;
}
}
更多信息请点击这里:https://mobx.js.org/react-integration.html
代码沙箱:https://codesandbox.io/s/httpsstackoverflowcomquestions64268663-9fz6b?file=/src/App.js
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)