Return ES6 和 React 中随时间变化的多个值

Return multiple values over time in ES6 & React

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

我需要这个,这样我就可以经常保持 returning 值。

我的代码如下:

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
    }
}

我的 React 组件

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

编辑:我正在寻求解决函数中此问题的解决方案,例如 python 答案: Return multiple values over time 但使用 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 )

您可以在 life-cycle 钩子中使用 setInterval。这将每隔一段时间重复调用该函数

  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
        }
    }

componentWillMount(){}

中添加setInerval
componentWillMount(){
  setInterval(()=>{
      this.loopingTitleTextHandler()
 }, 3000) // 3000 milli seconds, that is 3 sec
 }

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

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

App.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;

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

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