简体   繁体   中英

ReactJS: setTimeout not working inside map to render component

I want to render my ChatBubble component after an amount of time. But it does not return my component. Instead it returns numbers 2 and 3 as a string.

const Conversation = ({data}) => {
  const { messages } = data;

  return (
    <div>
      {
        messages.map(data => {
          return setTimeout(() => {
            return <ChatBubble key={uniqid()} data={data}/>
          }, data.delay);
        })
      }
    </div>
  );
}

export default Conversation;

Cause setTimeout returns the id of the timer. You cannot just return something to react and expect some magic to happen. Instead you probably need a stateful conponent like this:

class Conversation extends React.Component {
  constructor(props) {
    super(props);
    this.state = { messages: [] };
  }

  render() {
    return this.state.messages.map(data => (<ChatBubble {...data} />));
  }

  componentDidMount() {
     const {messages, delay} = this.props.data;
     this.interval = setInterval(() => {
       this.setState(prev => ({ messages: prev.messages.concat(messages.shift()) }));
       if(!messages.length) clearInterval(this.interval);
     }, delay);
  }

  componentWillUnmount() {
    clearInterval(this.interval);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM