Delay array map iteration in React

有些话、适合烂在心里 提交于 2019-12-04 01:44:56

问题


I have this array, that I want to iterate. I need to delay it by a couple of seconds before the next.

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

The initial state of this array is always more than one. For UI purposes I want them to load in one by one in to the DOM.


回答1:


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)
  }

})


来源:https://stackoverflow.com/questions/37372577/delay-array-map-iteration-in-react

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