React中的延迟数组映射迭代 [英] Delay array map iteration in React

查看:79
本文介绍了React中的延迟数组映射迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要迭代的数组.我需要将其延迟几秒钟.

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

此数组的初始状态总是不止一个.为了实现UI,我希望它们一一加载到DOM中.

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.

推荐答案

react的呈现功能是同步的. javascript映射也是同步的.因此,在这里使用计时器不是正确的解决方案.

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

但是,您可以在组件状态下跟踪已渲染的项目并使用javascript计时器更新该状态:

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

})

这篇关于React中的延迟数组映射迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆