【问题标题】:Delay array map iteration in React在 React 中延迟数组映射迭代
【发布时间】:2016-09-19 05:55:51
【问题描述】:

我有这个数组,我想迭代。我需要在下一次之前将其延迟几秒钟。

{this.props.things.map((thing, index) => {
   return (
     <div key={index}>{thing.content}</div>
     // Delay 1 second here
   )
})}

这个数组的初始状态总是不止一个。出于 UI 目的,我希望它们一一加载到 DOM 中。

【问题讨论】:

  • 为什么.map需要延迟?你能澄清一下问题吗
  • 具体说明您要在相当高的水平上实现的目标,以及为什么您得出需要延迟的结论?
  • 这个数组的初始状态总是不止一个。出于 UI 目的,我希望它们在初始渲染时一一加载。
  • 为什么不使用 CSS 将它们动画化?

标签: javascript reactjs jsx


【解决方案1】:

react 的渲染函数是同步的。 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)
  }

})

【讨论】:

  • 固体溶液。效果很好。谢谢。
猜你喜欢
  • 2015-04-04
  • 1970-01-01
  • 1970-01-01
  • 2016-04-10
  • 2013-12-17
  • 2014-05-17
  • 2013-01-13
  • 2011-07-16
相关资源
最近更新 更多