Javascript 运行时显示每个测试的状态

Javascript 运行时显示每个测试的状态,javascript,reactjs,ecmascript-6,lifecycle,Javascript,Reactjs,Ecmascript 6,Lifecycle,我有一个列表组件。 此组件从数据集接收数据。 当为每个测试运行回调函数时, 状态testStatus已更新。 console.logtestStatus记录以下内容 但是我在如何访问它们并相应地更新UI方面还是一片空白。 非常感谢您的帮助 我想在UI中显示不同的状态。 因此,当运行显示“测试正在运行”时 失败时显示“测试失败”。 通过时显示“测试成功”。 当所有测试完成并运行时,显示 '所有测试都在运行中完成' {!clicked && (

我有一个列表组件。 此组件从数据集接收数据。 当为每个测试运行回调函数时, 状态testStatus已更新。 console.logtestStatus记录以下内容

但是我在如何访问它们并相应地更新UI方面还是一片空白。 非常感谢您的帮助

我想在UI中显示不同的状态。 因此,当运行显示“测试正在运行”时 失败时显示“测试失败”。 通过时显示“测试成功”。 当所有测试完成并运行时,显示 '所有测试都在运行中完成'

             {!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的了解有点陈旧

所以请教育我。

事实上,您目前使用的构造函数方法太旧了。就像麦当娜唱圣诞歌一样。因此,为了更好地更新组件,我建议您阅读React钩子或有状态组件以及生命周期方法

不过,您可以使用useState&&useffect来更新此组件或组件将更新| | | PureComponent | | React.Memo。给它一个谷歌,你会发现那里有魔力

另外,请使用解构和赋值来提取{Component},这样就不需要再使用.bind了

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