首页 > 解决方案 > 在 ES6 和 React 中随时间返回多个值

问题描述

好的,那么有没有办法从函数返回一个值 - return 的方式 - 但不停止函数 - return 的方式?

我需要这个,所以我可以经常返回值。

我的代码如下所示:

loopingTitleTextHandler = () => {
    const title = ["good", "cool", "887H", "Vertical"];
    for (i = 0; i < 999999; i++) {
        var j = i%4;
        // loopingTitleTextHandler() // calls itself before return terminates execution 
        return title[j]; //return 0,1,2,3 in a loop with 3 second delay
    }
}

我的反应组件

<ShowTitle size={230}
    title={this.loopingTitleTextHandler()}
    color="#FDA7DC" />

编辑:我正在寻找一个在函数中解决这个问题的解决方案,比如这个 python 答案: Return multiple values over time but using ES6。

import time

def myFunction(limit):
    for i in range(0,limit):
        time.sleep(2)
        yield i*i

for x in myFunction(100):
    print( x )

标签: reactjsecmascript-6timeoutes6-promise

解决方案


在 React 的上下文中,我认为通过状态来管理这些值会更有意义。假设您想每 3 秒返回一个新标题,您可以执行以下操作:

这是一个沙箱:https ://codesandbox.io/s/elated-rgb-n4j6z

应用程序.js

import React from "react";
import ReactDOM from "react-dom";
import ShowTitle from "./ShowTitle";

import "./styles.css";

class App extends React.Component {
  state = {
    title: ["good", "cool", "887H", "Vertical"],
    currentTitle: "good"
  };

  loopingTitleTextHandler = () => {
    const { currentTitle, title } = this.state;
    const nextTitleIndex =
      title.indexOf(currentTitle) + 1 === title.length
        ? 0
        : title.indexOf(currentTitle) + 1;

    this.setState({ currentTitle: title[nextTitleIndex] });
  };
  render() {
    return (
      <div className="App">
        <ShowTitle
          changeTitle={this.loopingTitleTextHandler}
          currentTitle={this.state.currentTitle}
        />
      </div>
    );
  }
}

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

ShowTitle.js

import React from "react";

class ShowTitle extends React.Component {
  componentDidMount() {
    setInterval(() => {
      this.props.changeTitle();
      console.log(this.props.currentTitle + " " + new Date().getTime());
    }, 3000);
  }

  render() {
    return <div>Title: {this.props.currentTitle}</div>;
  }
}

export default ShowTitle;

在父组件 (App.js) 中,我们跟踪currentTitle. 当loopingTitleTextHandler()被调用时,我们用数组中的下一个标题更新我们的 state.currentTitle。currentTitle被传递给ShowTitle组件。

在 Child 组件中,我们使用 a每 3 秒setInterval()调用loopingTitleTextHandler()一次,并显示下一个标题。


推荐阅读