javascript - 运行时显示每个测试的状态
问题描述
我有一个列表组件。该组件从数据集中接收数据。当每个测试运行一个回调函数时,状态(testStatus)被更新。console.log(testStatus) 记录以下内容
但我对如何访问它们并相应地更新 UI 持空白。非常感谢任何帮助!
我想在 UI 中显示不同的状态。所以运行时显示'test is running' 失败时显示'Test failed'。通过时显示“测试成功”。当所有测试都运行完毕后,显示“所有测试都运行完毕”
{!clicked && (
<span style={{ background: "grey" }}>
Test did not run yet
</span>
)}
这是导入数据集和调用回调的列表组件。
import React from "react";
import "./App.css";
import tests from "../constants/tests/tests";
class TestsList extends React.Component {
constructor(props) {
super(props);
this.state = {
clicked: false,
testStatus: {},
tests: tests
};
this.handleClick = this.handleClick.bind(this);
}
uniqueId() {
tests.map((test, index) => {
let uniqId = parseInt(index);
return Object.assign(test, { id: uniqId });
});
}
handleClick(event) {
event.preventDefault();
this.uniqueId();
this.setState({ clicked: true });
tests.map(test => {
test.run(x =>
this.setState({
testStatus: {
...this.state.testStatus,
[test.id]: x ? "passed" : "failed"
}
})
);
});
}
render() {
const { clicked, testStatus, tests } = this.state;
console.log(testStatus);
return (
<div>
<div className="testsList">
{tests.map((test, index) => {
return (
<div key={test.description}>
<div style={{ display: "flex", flexDirection: "column" }}>
<p>{test.description}</p>
{!clicked && (
<span style={{ background: "grey" }}>
Test did not run yet
</span>
)}
{/* if the index is equal to the test.id */}
{/* {this.state.testStatus} */}
{/* {<span>{Object.values(testStatus)}</span>} */}
</div>
</div>
);
})}
</div>
<button className="testRunner" onClick={this.handleClick}>
Run these tests
</button>
</div>
);
}
}
export default TestsList;
我想我必须对生命周期钩子做一些事情。我对 React 的了解有点老旧。
所以请教育我。
解决方案
实际上,constructor
您使用的方法目前太旧了。就像麦多娜唱圣诞歌曲一样。因此,为了以更好的方式更新您的组件,我建议您阅读有关React Hooks
或Stateful Components and Lifecycle Methods
.
不过,您可以使用useState && useEffect
更新此组件或ComponentWillUpdate || PureComponent || React.Memo
. 给它一个谷歌,你会在那里找到魔法。
奖励:请使用解构和赋值来提取{ Component }
,不再需要使用.bind
。
这些提示可能会帮助您像专业人士一样编码!
推荐阅读
- python - 关键错误:[Int64Index([...]dtype='int64')] 都不在 [columns] 中
- python - 从多进程损坏文件记录?
- ios - 基于网页元颜色ios设置状态栏颜色
- java - 如何跳过特定的循环循环?
- javascript - 错误:等待仅在异步函数中有效
- html - 浏览器是否默认在后台将 HSL 转换为 RGB?
- assembly - 如何在 lldb 上打印程序集全局字符串变量
- python - 如何在python中按照确切的术语打印单词
- javascript - 条件渲染在我的功能组件中不起作用
- node.js - 所以我试图使用 discord.js V12 发出禁令命令,无论如何我总是遇到同样的错误