最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Delay array map iteration in React - Stack Overflow

programmeradmin0浏览0评论

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.

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.

Share Improve this question edited May 22, 2016 at 11:03 Willi Mentzel 30k21 gold badges118 silver badges127 bronze badges asked May 22, 2016 at 9:27 themolluskthemollusk 4404 silver badges10 bronze badges 4
  • 1 why do you need delay in .map? could you clarify issue – Oleksandr T. Commented May 22, 2016 at 9:28
  • Specify what you're trying to achieve at a reasonably high level, and why you have e to the conclusion that a delay is required? – christopher Commented May 22, 2016 at 9:32
  • The initial state of this array is always more than one. For UI purposes I want them to load in one by one on the initial render. – themollusk Commented May 22, 2016 at 9:35
  • 2 Why not animate them into view with CSS? – sdgluck Commented May 22, 2016 at 9:52
Add a ment  | 

1 Answer 1

Reset to default 6

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

  ponentDidMount() {
    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()
    }
  },

  ponentWillUnmount() {
    clearTimeout(this.timer)
  }

})
发布评论

评论列表(0)

  1. 暂无评论