在 ES6 和 React 中随时间返回多个值



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

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

我的代码如下所示:

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答案:随时间返回多个值但使用 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 )

在 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);

显示标题.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 组件中,我们使用一个setInterval()每 3 秒调用一次loopingTitleTextHandler(),并显示下一个标题。

您可以在生命周期钩子中使用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
 }

最新更新