togglePreloader: function(toggleState) {
var timeout = null;
var time = 0;
if (toggleState) {
if (this.state.preloading) console.log("Preloader alredy shown");
if (timeout) {
clearTimeout(timeout);
timeout = null;
} else if (!this.state.preloading) {
console.log("Show preloader");
time = Date.now();
this.setState({ preloading: true });
}
} else {
if (!timeout) {
var elapsed = Date.now() - time;
if (elapsed < Config.PRELOADER_MIN_DISPLAY_DURATION) {
console.log("Preloader hiding timeout was started; elapsed: " + elapsed + "/" + Config.PRELOADER_MIN_DISPLAY_DURATION);
timeout = setTimeout(function() {
timeout = null;
this.setState({ preloading: false });
console.log("Hide preloader by timeout");
}.bind(this), Config.PRELOADER_MIN_DISPLAY_DURATION - elapsed);
} else {
this.setState({ preloading: false });
console.log("Hide preloader; elapsed: " + elapsed + "/" + Config.PRELOADER_MIN_DISPLAY_DURATION);
}
} else console.log("Preloader hiding is waiting for timeout");
}
}
这是reactJs组件的方法。它触发显示和隐藏预加载器。如果预加载器的显示时间小于最短持续时间(例如 500 毫秒),则会设置隐藏超时。
问题是在 togglePreloader 调用之间将变量 timeout 和 time 存储在哪里。改变 this.props 并不是一个好主意。 this.state 的更改会触发重新渲染。将变量移出组件?或者将状态与 shouldComponentUpdate 一起使用?什么是最好的方法 ?我是 ReactJs 新手
最佳答案
这不仅不是一个好主意,您也无法使用 this.props
,它是组件父级控制的数据集合。您可以使用将呈现的状态,或者您可以只做显而易见的事情:只需使用 this.timeout = ...
,因为您的 React 组件仍然只是一个具有自己的实例范围的 JavaScript 对象.
this.props.xyz
表示“从上面”分配给您的值this.state.xyz
用于您控制并直接影响 UI 外观的值this.xyz
用于对 UI 没有影响的任何 transient 值,并且在技术上可以重置而不会产生任何不利影响。
但是,考虑到超时值是通用的,因此可能应该是静态的:
var YourComponent = React.createClass({
statics: {
timeout: 500
},
...
checkStuff: function() {
if (this.currentTime >= YourComponent.timeout) {
this.doAThing();
}
},
...
});
如果想法是 UI 会根据超时发生不同的事情,那么您实际上应该触发一些 state
值,然后您的组件可以在 render()
以确保它现在显示或执行正确的操作。因此,您使用 this.currentTime
来跟踪到目前为止的时间,然后在您知道超过阈值后使用状态变量。
如果您是 React 新手,那么 100% 值得浏览一下 React 网站上的“入门”和“教程”部分。只需坐下来,一次性完成所有操作(不到 30 分钟),您就会更好地了解应该如何使用 React。如果您仍然需要更多见解,Google 上有很多关于 React 的精彩文章。
关于javascript - 在 ReactJs 组件方法调用之间存储变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31520377/