我试图从Redux转移到Mobx,并尝试在mobx存储中设置一个数组,我使用装饰器来设置值。我能够从存储中返回静态值,但是下面的数组长度总是抛出未定义的值。 不知道下面的代码有什么问题。有什么建议吗?
import {observable, action, computed} from 'mobx';
class FormDataStore {
@observable formdata = [1,2,3];
@action updateFormData = (formdata) => {
this.formdata.push(formdata);
}
@computed get readdata() {
return this.formdata.length;
}
}
const store = new FormDataStore();
export default store
错误
FormDataStore.js:12 Uncaught TypeError: Cannot read property 'length' of undefined
at FormDataStore.get (FormDataStore.js:12)
at trackDerivedFunction$$1 (mobx.module.js:1142)
at ComputedValue$$1.computeValue (mobx.module.js:934)
at ComputedValue$$1.trackAndCompute (mobx.module.js:919)
at ComputedValue$$1.get (mobx.module.js:879)
at ObservableObjectAdministration$$1.read (mobx.module.js:3822)
at FormDataStore.get (mobx.module.js:4086)
at FormDataStore.get (mobx.module.js:295)
at PreviewWindow.render (PreviewWindow.js:24)
at Object.allowStateChanges$$1 (mobx.module.js:653)
以下是我尝试读取数据
的方法import React from "react";
import { Container } from "semantic-ui-react";
import Highlight from "react-highlight";
import {inject,observer} from 'mobx-react';
@inject('FormDataStore')
@observer
class PreviewWindow extends React.Component {
render() {
const {FormDataStore} = this.props;
console.log(FormDataStore)
return (
<Container>
<h1>JSon Preview</h1>
<h1>{FormDataStore.getFormData}</h1>
<Highlight language="javascript">{FormDataStore.readdata}</Highlight>
</Container>
);
}
}
export default PreviewWindow;
答案 0 :(得分:0)
.babelrc
中插件的顺序很重要,必须更改babel config中插件的顺序才能解决此问题。
/// WRONG
"plugins": [
"transform-class-properties",
"transform-decorators-legacy"
]
// RIGHT
"plugins": [
"transform-decorators-legacy",
"transform-class-properties"
]