简体   繁体   English

通过延迟响应通过字符串数组循环并设置文本值

[英]react loop through array of strings with delay and set the text value

I have a loader which shows loading message when passed a string, but when passed an array I want to show multiple messages one after another looping through messages array. 我有一个加载器,它在传递字符串时显示加载消息,但是在传递数组时,我想一个接一个地循环显示消息数组来显示多个消息。

const messages = ['fetching from sources...', 'loading account...'];

<Loader message={messages}/>

const Loader = (Props) => {
    const { message } = props;


    const renderMessages = (msgs) => {

        console.log(msgs);
        return msgs.forEach((msg, i) => {
            setTimeout(() => {
                return <Message>{msg}</Message>;
            }, 500);
        });
    };

    return (
        <LoaderContainer>
            <LoaderSvg width="120" height="120" viewBox="0 0 100 100" />
            {(Array.isArray(message)) ? renderMessages(message) : <Message>{message}</Message>}

        </LoaderContainer>
    );
};

Here's an example of what could work for you: https://codesandbox.io/s/loop-through-array-with-react-d5tlc (I would suggest reviewing it for edge cases but the core functionality should be close to what you're looking for). 这是一个适用于您的示例: https : //codesandbox.io/s/loop-through-array-with-react-d5tlc (我建议您对它进行一些边缘检查,但核心功能应与您的情况相近正在寻找)。

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

const messages = ["fetching from sources...", "loading account..."];

const Loader = props => {
  const { messages } = props;
  // Default to the first message passed
  const [messageIndex, setMessageIndex] = React.useState(0);

  React.useEffect(() => {
    // Move on to the next message every `n` milliseconds
    let timeout;
    if (messageIndex < messages.length - 1) {
      timeout = setTimeout(() => setMessageIndex(messageIndex + 1), 1000);
    }

    return () => {
      clearTimeout(timeout);
    };
  }, [messages, messageIndex]);

  return <div>{messages[messageIndex]}</div>;
};

function App() {
  return (
    <div className="App">
      <Loader messages={messages} />
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

A functional component has to return the jsx to render. 功能组件必须返回jsx进行渲染。 What you are trying to do does not work. 您尝试执行的操作无效。 In case of an array of messages you are returning msgs.forEach(...) but Array.prototype.forEach does not return an array but undefined . 如果是消息数组,则返回msgs.forEach(...)Array.prototype.forEach不返回数组,但返回undefined

You will need to use state to queue up the messages one by one and render the contents of that state instead. 您将需要使用状态将消息一一排队,然后呈现该状态的内容。

You can append message in a variable and return that variable in renderMessage function 您可以在变量中附加消息,然后在renderMessage函数中返回该变量

const renderMessages = (msgs) => {
    let msgList = ""
    console.log(msgs);
    return msgs.forEach((msg, i) => {
        msgList = msgList + "/n" + msg
        setTimeout(() => {
            return <Message>{msgList}</Message>;
        }, 500);
    });
};

/n will show next message in new line / n将在新行中显示下一条消息

What does you program not do as expected? 您编程的内容与预期不符吗? Do the messages not show? 消息不显示吗?

If you want to render some element while iterating through an aray, i would advise to use array.map() rather than array.forEach() . 如果要在遍历aray时呈现某些元素,我建议使用array.map()而不是array.forEach()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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