Delay array map iteration in React

前端 未结 1 1617
时光取名叫无心
时光取名叫无心 2021-01-14 02:36

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         


        
1条回答
  •  醉梦人生
    2021-01-14 03:03

    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 (
          
    { this.state.renderedThings.map((thing, index) => (
    {thing.content}
    )) }
    ) }, 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) } })

    0 讨论(0)
提交回复
热议问题