首页 > 解决方案 > 运行时显示每个测试的状态

问题描述

我有一个列表组件。该组件从数据集中接收数据。当每个测试运行一个回调函数时,状态(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 的了解有点老旧。

所以请教育我。

标签: javascriptreactjsecmascript-6lifecycle

解决方案


实际上,constructor您使用的方法目前太旧了。就像麦多娜唱圣诞歌曲一样。因此,为了以更好的方式更新您的组件,我建议您阅读有关React HooksStateful Components and Lifecycle Methods.

不过,您可以使用useState && useEffect更新此组件或ComponentWillUpdate || PureComponent || React.Memo. 给它一个谷歌,你会在那里找到魔法。

奖励:请使用解构和赋值来提取{ Component },不再需要使用.bind

这些提示可能会帮助您像专业人士一样编码!


推荐阅读