Javascript 如何在 Reactjs 中添加延迟
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42089548/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add delay in Reactjs
提问by shubham agrawal
I am new to Reactjs. I am not sure how to add delayto render in Reactjs.What is the best way to add delay.
我是 Reactjs 的新手。我不确定如何添加delay到渲染中Reactjs。添加延迟的最佳方法是什么。
I am adding the following code in render but its not working.
我在渲染中添加以下代码但它不起作用。
setTimeout(function() {
}, 1000);
回答by Rob van Dijk
Not sure why you would want to do this, but something like this?
不知道你为什么要这样做,但像这样的事情?
The component's constructor:
组件的构造函数:
constructor(props) {
super(props);
this.state = {
render: false //Set render state to false
}
}
On component mount:
在组件安装上:
componentDidMount() {
setTimeout(function() { //Start the timer
this.setState({render: true}) //After 1 second, set render to true
}.bind(this), 1000)
}
The render method:
渲染方法:
render() {
let renderContainer = false //By default don't render anything
if(this.state.render) { //If this.state.render == true, which is set to true by the timer.
renderContainer = <div>Look at me! I'm content!</div> //Add dom elements
}
return (
renderContainer //Render the dom elements, or, when this.state == false, nothing.
)
}
So when the timer fires, render is set to true. Because render is stored in state, this also triggers a re-render of the component. The if statement simply instructs renderContainer to not display anything unless the state render is true. You could also show a text indicating the component is loading, by instead of declaring renderContainer= falseat the top, declaring the default as renderContainer=<div>Component is loading..</div>for example.
所以当定时器触发时,render 设置为 true。因为渲染存储在状态中,这也会触发组件的重新渲染。if 语句只是指示 renderContainer 不显示任何内容,除非状态 render 为真。您还可以显示一个文本指示组件正在加载,而不是renderContainer= false在顶部声明renderContainer=<div>Component is loading..</div>,例如声明默认值。

