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
1 Answer
Reset to default 6The 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)
}
})
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744966800a4603730.html
评论列表(0条)