You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React如何每秒从数组中渲染一个元素?附示例代码

Rendering One Element Per Second from an Array in React (Including Redux Integration)

Hey there! Let's fix this so you can render one word from your array every second—even when that array comes from Redux. Your current code maps all elements at once, so we need to add state to control how many elements are visible over time. Here's how to do it:

Class Component Solution (Matching Your Original Code)

First, let's adjust your class component to track which words should be visible using component state, and use a timer to update that state every second. We'll also handle cleanup to avoid memory leaks, and add support for Redux-provided arrays.

class Message extends React.Component {
  constructor(props) {
    super(props);
    // Track how many words we've rendered so far
    this.state = {
      currentIndex: 0,
    };
    this.timer = null; // Store timer reference for cleanup
  }

  componentDidMount() {
    // Start the timer when the component mounts
    this.startTimer();
  }

  componentDidUpdate(prevProps) {
    // If the array from Redux changes, reset our progress and restart the timer
    if (prevProps.arrWords !== this.props.arrWords) {
      if (this.timer) clearInterval(this.timer);
      this.setState({ currentIndex: 0 }, () => this.startTimer());
    }
  }

  componentWillUnmount() {
    // Clean up the timer when the component unmounts
    if (this.timer) clearInterval(this.timer);
  }

  startTimer = () => {
    this.timer = setInterval(() => {
      this.setState(prevState => {
        // Stop the timer once all words are visible
        if (prevState.currentIndex >= this.getWords().length - 1) {
          clearInterval(this.timer);
          return prevState;
        }
        // Increment the index to show one more word
        return { currentIndex: prevState.currentIndex + 1 };
      });
    }, 1000); // Update every 1 second
  };

  getWords = () => {
    // Use Redux-provided array if available, fall back to local array
    return this.props.arrWords || ["I", "would", "like", "to", "print", "one", "word", "per", "second"];
  };

  renderWord(word, index) {
    return <span key={index}> {word} </span>;
  }

  renderWords() {
    // Only render words up to the current index
    const visibleWords = this.getWords().slice(0, this.state.currentIndex + 1);
    return visibleWords.map((word, index) => this.renderWord(word, index));
  }

  render() {
    return <div>{this.renderWords()}</div>;
  }
}

Function Component + Hooks Solution (Modern Approach)

If you're open to using function components (which are more common now), here's a cleaner version using useState and useEffect:

import { useState, useEffect } from 'react';

const Message = ({ arrWords }) => {
  const [currentIndex, setCurrentIndex] = useState(0);
  // Fallback to local array if Redux prop isn't provided
  const words = arrWords || ["I", "would", "like", "to", "print", "one", "word", "per", "second"];

  useEffect(() => {
    // Reset index when the array changes
    setCurrentIndex(0);

    const timer = setInterval(() => {
      setCurrentIndex(prevIndex => {
        if (prevIndex >= words.length - 1) {
          clearInterval(timer);
          return prevIndex;
        }
        return prevIndex + 1;
      });
    }, 1000);

    // Cleanup timer when component unmounts or array changes
    return () => clearInterval(timer);
  }, [words]);

  const renderWord = (word, index) => <span key={index}> {word} </span>;
  const visibleWords = words.slice(0, currentIndex + 1);

  return <div>{visibleWords.map(renderWord)}</div>;
};

Key Notes:

  • State Tracking: We use currentIndex to track how many elements should be visible. Every second, we increment this index until all elements are shown.
  • Timer Cleanup: Always clear the interval when the component unmounts or when the array changes—this prevents memory leaks and unexpected behavior.
  • Redux Integration: By watching the arrWords prop (in componentDidUpdate for class components, or in the useEffect dependency array for function components), we reset the timer and state whenever the Redux store updates the array.

内容的提问来源于stack exchange,提问作者ugocasalone

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:29:22