Class 定义getter而不使用setter ecma6-react
React-ecma6 dosent似乎允许定义无设置器的getter 有没有一种方法可以定义一个getter-only方法并通过任何其他方法更改一个值Class 定义getter而不使用setter ecma6-react,class,reactjs,compiler-errors,ecmascript-6,getter-setter,Class,Reactjs,Compiler Errors,Ecmascript 6,Getter Setter,React-ecma6 dosent似乎允许定义无设置器的getter 有没有一种方法可以定义一个getter-only方法并通过任何其他方法更改一个值 import React from 'react'; export default class GetterOnly extends React.Component { constructor(props) { super(props); this._is_on = false; } o
import React from 'react';
export default class GetterOnly extends React.Component {
constructor(props) {
super(props);
this._is_on = false;
}
on() {
this._is_on = true;
}
get is_on() {
return this._is_on;
}
render() {
}
}
var _getter = new GetterOnly()
_getter.on();
未捕获的TypeError:无法设置属性位于的
它只有一个getter
patchProperty@makeAssimilatePrototype.js:21(匿名)
函数)@makeAssimilatePrototype.js:52(匿名)
函数)@makeAssimilatePrototype.js:51
reconcileWithStoredPrototypes@makeAssimilatePrototype.js:50
assimilatePrototype@makeAssimilatePrototype.js:63
patchReactClass@makePatchReactClass.js:40
makeHot@makeMakeHot.js:33 makeExportsHot@makeExportsHot.js:44
(匿名函数)@GetterOnly.js:139(匿名
函数)@GetterOnly.js:139(匿名函数)@GetterOnly.js:140
(匿名函数)@app.js:5062
webpack\u require@app.js:556 fn@app.js:87(匿名函数)@page.js:35(匿名函数)@page.js:81(匿名函数)
函数)@page.js:82(匿名函数)@app.js:5056
webpack\u require@app.js:556 fn@app.js:87(匿名函数)@Routes.js:19(匿名函数)@Routes.js:52
(匿名函数)@Routes.js:53(匿名函数)@app.js:4438
webpack\u require@app.js:556 fn@app.js:87(匿名函数)@makoVOD.js:19(匿名函数)@makoVOD.js:62
(匿名函数)@makoVOD.js:63(匿名)
函数)@app.js:1042
webpack\u require@app.js:556 fn@app.js:87(匿名函数)@multi\u main:3(匿名函数)@app.js:586
webpack\u require@app.js:556(匿名函数)@app.js:579(匿名函数)@app.js:582
问题是您正在调用上的
作为函数。getter使函数看起来像属性:
所以最后一行应该是\u getter.on
而不是\u getter.on()
另外,要使\u成为变量private,可以在类外定义它,如下所示:
import React from 'react';
let _is_on = false;
export default class GetterOnly extends React.Component {
constructor(props) {
super(props);
}
on() {
_is_on = true;
}
get is_on() {
return _is_on;
}
render() {
}
}
var _getter = new GetterOnly()
_getter.on;
现在,除了类之外,没有人可以编辑变量。问题不是React/Es6 Responsibility。它似乎来自nodejs-webpack。热。。。我用来自动传输代码的模块。
我已经升级到vesion:2.0.0-alpha,错误消失了。
这是一个已知的问题-
不,这是允许的-这不是语法错误。您收到的错误消息表明确实有东西试图分配给.is\u on
,这会在没有setter的情况下引发异常。检查错误的堆栈跟踪以查看其来源。这是代码的简化版本,但仍然显示错误:import React from'React';类GetterOnly扩展React.Component{constructor(props){super(props);};get is_on(){return this._is_on;};render(){};}export default GetterOnly
这似乎是导入/导出模块的问题我非常确定导出过程没有设置属性。向我们展示导入和使用该类的位置。请在你的帖子中加入堆栈跟踪。我想我发现了问题,它在网页中。热。。。单元升级到vesion:2.0.0-alpha,错误消失on
确实是一种方法,应该调用它let_is_on=false代码>将在所有实例之间共享此标志。