我正在尝试使用Mobx构建一个简单的计数器。我可以看到它正在更新类中的值,但更新的值没有在react视图中更新。
这是我的代码
import {observable} from 'mobx';
import {observer} from 'mobx-react';
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
class CounterStore {
@observable counter;
constructor(){
this.counter = 0;
}
increase(){
this.counter++;
}
decrease(){
this.counter--;
}
}
@observer
class Counter extends Component {
render(){
const counter = this.props.counter;
return(
<div style={{display: 'flex'}}>
<button onClick={counter.increase.bind(counter)}>+</button>
<p style={{color: 'black', marginRight: '1rem', marginLeft: '1rem'}}>{counter.counter}</p>
<button onClick={counter.decrease.bind(counter)}>-</button>
</div>
);
}
}
const store = new CounterStore();
ReactDOM.render(
<Counter counter={store} />,
document.getElementById('app')
);
答案 0 :(得分:2)
我刚刚在JSFiddle中尝试过你的代码,它似乎运行没有问题?