reactjs - 在 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 )
解决方案
在 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()
一次,并显示下一个标题。
推荐阅读
- powershell - 递归捕获所有 ADGroup 和成员的 Powershell 脚本
- c# - 将框架升级到 .NET Core 3.1 后出现 Swagger 问题
- python - 如何将列表与交替元素合并?
- cypress - 将 guid 传递给 API 请求
- bash - 在shell中,为什么“2>err&”允许脚本在后台运行?
- c# - 如何捕获无服务器 SQL Server 冷启动的异常
- node.js - QueryFailedError: ORA-14148: DML 和 DDL 操作不允许在保护列上直接进行。(nestjs + typeorm )
- python - json解码错误期望值:第1行第1列(char 0)
- javascript - VS-Code 设置 json 的 json 架构是什么?
- java - 我应该在对象创建后立即初始化我的实体字段吗?