【发布时间】:2018-12-08 23:16:38
【问题描述】:
这个问题实际上与 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)吗?或者也许我应该以不同的方式做到这一点?最佳做法是什么?
【问题讨论】:
-
变量“thing”是一个变量类,在这个类中定义的所有方法都可以访问它。如果你在你的状态下对其进行罚款也是一样的: state = { value: "...", thing: null }
-
你可以查看medium.freecodecamp.org/… 就像你正在做的那样使用
this看起来是一个不错的选择 -
@DaniloAssisNobredosSantos 如果对
thing的更改一定会触发重新渲染,这只是一个好主意——否则,我认为最好将thing存储在其他地方
标签: javascript reactjs class