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

时间:2019-10-02 15:37:19

标签: javascript reactjs ecmascript-6 lifecycle

我有一个列表组件。 该组件从数据集中接收数据。 对于每个测试,在运行回调函数时, 状态(testStatus)已更新。 console.log(testStatus)记录以下内容 enter image description here

但是我在如何访问它们以及相应地更新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的了解有点陈旧和生锈。

所以请教育我。

1 个答案:

答案 0 :(得分:1)

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

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

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

这些技巧可能会帮助您像专家一样编写代码!