问题描述
使用Mobx,在更新商店(即单击按钮)后,该组件不会重新呈现.我已经安装了mobx devtools,它在初始加载后什么也不显示,并且在控制台中没有错误.有任何想法我做错了吗?
Using Mobx, after updating the store (i.e. clicking the button) the component does not re-render. I've installed mobx devtools which shows nothing after the initial load, and there is no error in the console. Any ideas what I've done wrong?
Store.js:
import { observable } from 'mobx';
class Store {
@observable me;
constructor() {
this.me = 'hello';
}
change_me(){
this.me = 'test 1234';
}
}
export default Store;
layout.js:
layout.js:
import React from "react";
import { observer } from 'mobx-react';
@observer
export default class Layout extends React.Component{
render(){
return(
<div>
<h1>{this.props.store.me}</h1>
<button onClick={this.on_change}>Change</button>
</div>
)
}
on_change = () => {
this.props.store.change_me();
}
}
index.js:
import React from "react";
import ReactDOM from "react-dom";
import Layout from "./components/Layout";
import Store from "./Store";
import DevTools, { configureDevtool } from 'mobx-react-devtools';
// Any configurations are optional
configureDevtool({
// Turn on logging changes button programmatically:
logEnabled: true,
// Turn off displaying conponents' updates button programmatically:
updatesEnabled: false,
// Log only changes of type `reaction`
// (only affects top-level messages in console, not inside groups)
logFilter: change => change.type === 'reaction',
});
const app = document.getElementById('app');
const store = new Store();
ReactDOM.render(
<div>
<Layout store={store} />
<DevTools />
</div>
, app);
推荐答案
我首先将@action添加到您的change_me()函数中.据我了解,并不总是完全需要它,但是当我忘记添加它时,在自己的代码中几次遇到这样的问题.
I would start by adding @action to your change_me() function. From what I understand, it's not always completely required, but I have encountered problems like this in my own code several times when I've forgotten to add it.
另外按照@mweststrate的建议发布您的.babelrc,因为它将帮助其他人检查是否已加载正确的插件.
Additionally post your .babelrc as @mweststrate suggested, as it will help others to check that the proper plugins are loaded.
这篇关于React Mobx-商店更改后组件未更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!