使用Javascript在类方法中定义内部类变量



这个问题实际上与React JS有关。可以在其中一个类方法中定义内部类变量,然后在其他方法中使用它吗?我想做这样的事情:

class Something extends React.Component {
state = {
value: 'doesnt matter'
};
something = () => {
//a lot is happening in here and at some point I define this.thing
this.thing = 1;
}
increase = () => {
if(this.thing) {
this.thing += 1;
}
}
decrease = () => {
if(this.thing && this.thing > 0) {
this.thing -= 1;
}
}
render() {
return (
<span>this.state.value</span>
);
}
}

问题是,我不需要将this.thing作为状态值,因为我只需要在内部使用它。请注意,此代码只是一个示例,实际代码有点复杂,但主要问题是,可以像我在示例中那样定义类内部变量(this.thing(吗?或者也许我应该采取不同的做法?最佳做法是什么?

使用构造函数来做这样的事情不是问题,但基于react理论和UI渲染,这种使用不会重新渲染,也不会遵循触发器和重新渲染的react模式,它只是作为一个与react生命周期无关的值的存储服务器。

class Something extends React.Component {
constructor(props) {
super(props);
// Your thing
this.thing = 0;
this.state = {
value: "doesnt matter."
};
}
something = () => {
//a lot is happening in here and at some point I define this.thing
this.thing = 1;
};
increase = () => {
if (this.thing) {
this.thing += 1;
}
};
decrease = () => {
if (this.thing && this.thing > 0) {
this.thing -= 1;
}
};
render() {
this.something();
console.log(this.thing); // will equal 1.
return <span>{this.state.value}</span>;
}
}

我不需要把this.thing作为一个状态值,因为我只在内部需要它。

React组件的state也只能在内部使用。

最佳做法是什么?

您可以使用实例变量(ivar(而不是状态来提高性能,因为您可以减轻事件队列的负担。从美学上讲,ivar通常需要更少的代码。但状态更新通常是首选,因为它们会触发重新渲染;这种保证使您的代码更易于思考,因为渲染永远不会过时。在您的情况下,render函数独立于this.thing,因此可以将其存储在ivar中。

一般来说,最好在构造函数中初始化ivar,因为它首先运行,所以this.thing保证可以通过其他方法使用:

constructor(props) {
super(props);
this.thing = 0;
}

最新更新