我有这个数组,我想迭代.我需要在下一个之前将它延迟几秒钟.
{this.props.things.map((thing, index) => {
return (
<div key={index}>{thing.content}</div>
// Delay 1 second here
)
})}
此数组的初始状态始终不止一个.出于UI目的,我希望它们逐个加载到DOM中.
解决方法:
反应的渲染功能是同步的. javascript地图也是同步的.所以在这里使用计时器不是正确的解决方案.
但是,您可以在组件状态下跟踪已呈现的项目并使用javascript计时器更新该状态:
有关示例实现,请查看此fiddle:
React.createClass({
getInitialState() {
return {
renderedThings: [],
itemsRendered: 0
}
},
render() {
// Render only the items in the renderedThings array
return (
<div>{
this.state.renderedThings.map((thing, index) => (
<div key={index}>{thing.content}</div>
))
}</div>
)
},
componentDidMount() {
this.scheduleNextUpdate()
},
scheduleNextUpdate() {
this.timer = setTimeout(this.updateRenderedThings, 1000)
},
updateRenderedThings() {
const itemsRendered = this.state.itemsRendered
const updatedState = {
renderedThings: this.state.renderedThings.concat(this.props.things[this.state.itemsRendered]),
itemsRendered: itemsRendered+1
}
this.setState(updatedState)
if (updatedState.itemsRendered < this.props.things.length) {
this.scheduleNextUpdate()
}
},
componentWillUnmount() {
clearTimeout(this.timer)
}
})