![](/img/trans.png)
[英]Why can't we use React.useMemo in mobx-react to keep reference to the state object?
[英]Mobx-react no render but state changed
我决定尝试 Mobx 并面临组件对存储库中不断变化的字段缺乏响应的问题。 我看了类似的主题,但我仍然不明白问题是什么。 如果您在更改后将属性值打印到控制台,您会看到实际结果。
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from "mobx-react";
import AppStore from "./AppStore";
import App from './App';
ReactDOM.render(
<React.StrictMode>
<Provider AppStore={AppStore}>
<App />
</Provider>
</React.StrictMode>,
document.getElementById('root')
);
应用程序.js
import React, { Component } from "react";
import { inject, observer } from "mobx-react";
@inject('AppStore')
@observer class App extends Component {
render() {
const { AppStore } = this.props;
console.log(AppStore);
return(
<div className="App">
{ this.props.AppStore.counter }
<hr/>
<button onClick={this.props.AppStore.increment}>+</button>
<button onClick={this.props.AppStore.decrement}>-</button>
</div>
)
}
}
export default App;
应用商店.js
import { observable, action } from "mobx";
class AppStore {
@observable counter = 0;
@action increment = () => {
this.counter = this.counter + 1;
console.log(this.counter);
}
@action decrement = () => {
this.counter = this.counter - 1;
console.log(this.counter);
}
}
const store = new AppStore();
export default store;
由于mobx@6.0.0
装饰器是不够的。 您还必须使用 makeObservable 手动使您的makeObservable
可观察。
class AppStore {
@observable counter = 0;
constructor() {
makeObservable(this);
}
@action increment = () => {
this.counter = this.counter + 1;
}
@action decrement = () => {
this.counter = this.counter - 1;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.