Delay array map iteration in React

余生长醉 提交于 2019-12-01 09:13:29

The render function of react is synchronous. Also javascript map is synchronous. So using timers is not the right solution here.

You can however, in your component state, keep track of items that have been rendered and update that state using javascript timers:

For an example implementation check out this 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)
  }

})
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!