javascript - Mobx-react 无渲染但状态已更改
问题描述
我决定尝试 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
。
class AppStore {
@observable counter = 0;
constructor() {
makeObservable(this);
}
@action increment = () => {
this.counter = this.counter + 1;
}
@action decrement = () => {
this.counter = this.counter - 1;
}
}
推荐阅读
- python - 无法在 Python 中定位元素 - Selenium
- sql - 使用 (+) 在两个表之间进行左连接
- r - 在条件下使用默认参数调用函数
- php - 使用 JWT 身份验证包时 authentication_listener 不起作用
- java - Intellij 中的 Tesseract 无法读取 pdf,因为“gsdll64”库无法加载
- r - Worldclim:R中的getData()(纬度/经度坐标):utils :: unzip(zipfile,exdir = dirname(zipfile))中的错误:'exdir'不存在
- windows - 在运行作业时将控制台的输出消息分配给变量
- arrays - 如何在 React 的不同页面中传递数组值?
- python - 熊猫奇怪的平等行为
- mysql - Mysql 表太大,只有几行