.map中的嵌入式函数以访问映射的信息

时间:2020-02-24 14:39:00

标签: javascript reactjs

我正在使用.map函数向用户显示详细信息。 我想要一个按钮,以便在单击该按钮时可以展开,以向用户显示更多的深度信息。

在映射后,由于无法理解映射的信息(例如r.AssignedWorkStation

),我无法正常设置函数(在构造函数和渲染之间)

我基本上是在问是否可以在此处放置一个函数(下面的示例),然后使它能够访问映射的属性

const renderTodos = currentTodos.map(r => {
      Test(){
        if(me){
          //function to do what I want 

        }

      }
      return (
        <>
          <div className="jumbotron">
            <button className="btn btn-primary" style={{ float: "right" }}>
              View Details
            </button>

            <br />
            <li>
              <b>Workstation : </b>

              {r.AssignedWorkStation}
            </li>
            <li>
              <b>Date: </b>
              {r.Date}
            </li>

            <li>
              <b>Status: </b>
              {r.CompleteToken}
            </li>

            <br />

          </div>
        </>
      );
    });

整个课程代码



var results = [];
class AdminWorkstations extends React.Component {
  constructor() {
    super();

    this.state = {
      questions: [],
      viewDetails: false,

      currentPage: 1,
      todosPerPage: 4
    };
    this.getQuestionByUniqueDate = this.getQuestionByUniqueDate.bind(this);
    // this.test = this.test.bind(this);
  }
  // sets the questions form sql into state for questions
  handleClick = event => {
    this.setState({
      currentPage: Number(event.target.id)
    });
  };

  // test() {
  //   alert(r.AssignedWorkStation);
  // }

  componentDidMount() {
    fetch(`/admin-completed-workstations`)
      .then(recordset => recordset.json())
      .then(results => {
        this.setState({ questions: results.recordset });
        console.log(this.state.questions);

        this.state.questions &&
          this.getQuestionByUniqueDate(this.state.questions);
      });
  }

  handlePageChange(pageNumber) {
    this.setState({ activePage: pageNumber });
  }

  getQuestionByUniqueDate(questions) {
    for (var i = 0; i < questions.length; i++) {
      if (
        !results.find(q => q.Date == questions[i].Date) ||
        !results.find(
          q => q.AssignedWorkStation == questions[i].AssignedWorkStation
        )
      ) {
        results.push(questions[i]);
        this.setState({ amountOfWorkstations: results.length });
      }
    }
    return results;
  }

  render() {
    const { currentPage, todosPerPage } = this.state;

    // Logic for displaying current todos
    const indexOfLastTodo = currentPage * todosPerPage;
    const indexOfFirstTodo = indexOfLastTodo - todosPerPage;
    const currentTodos = results.slice(indexOfFirstTodo, indexOfLastTodo);
    debugger;

    const renderTodos = currentTodos.map(r => {



      return (
        <>
          <div className="jumbotron">
            <button className="btn btn-primary" style={{ float: "right" }}>
              View Details
            </button>

            <br />
            <li>
              <b>Workstation : </b>

              {r.AssignedWorkStation}
            </li>
            <li>
              <b>Date: </b>
              {r.Date}
            </li>

            <li>
              <b>Status: </b>
              {r.CompleteToken}
            </li>

            <br />
            {/* <Questions results={r}></Questions> */}
          </div>
        </>
      );
    });
    const pageNumbers = [];
    for (
      let i = 1;
      i <= Math.ceil(this.state.amountOfWorkstations / todosPerPage);
      i++
    ) {
      pageNumbers.push(i);
    }

    const renderPageNumbers = pageNumbers.map(number => {
      return (
        <button
          className="btn btn-primary"
          key={number}
          id={number}
          onClick={this.handleClick}
        >
          {number}
        </button>
      );
    });

    let selectedWorkStation = window.localStorage.getItem("Workstation");

    console.log(this.state.questions);

    if (this.state.questions.length) {
      return (
        <div>
          <h2 style={{ textAlign: "center" }}>
            Completed Workstation Assessments
          </h2>
          <ul>
            <button disabled className="btn btn-secondary">
              Workstation Assessments
            </button>
            <Link to="./admin-center">
              <button className="btn btn-secondary">Edit Questions</button>
            </Link>
            <Link to="./admin-center-view-users">
              <button className="btn btn-secondary">View Users</button>
            </Link>
            <DropdownButton
              style={{ float: "right" }}
              id="dropdown-basic-button"
              title="Completed"
            >
              <Dropdown.Item>
                {" "}
                <Link to="admin-view-workstation-assessments-declined">
                  In Progress
                </Link>
              </Dropdown.Item>
            </DropdownButton>{" "}
          </ul>

          <ul>
            {renderTodos}{" "}
            <div
              style={{ userSelect: "none", cursor: "pointer" }}
              id="page-numbers"
            >
              {renderPageNumbers}
            </div>
          </ul>
        </div>
      );
    } else if (!this.state.questions.length) {
      return (
        <>
          {" "}
          <div>
            <h3 style={{ textAlign: "center" }}></h3>

            <ul>
              <br />
              <br />{" "}
              <div>
                <h6>
                  {" "}
                  <tr>
                    Desk Location Selected :{" "}
                    <u style={{ color: "grey" }}>{selectedWorkStation}</u>
                  </tr>
                </h6>
              </div>
              <div className="jumbotron">
                <li style={{ textAlign: "center" }}>
                  <b>no completed Workstation Self-Assessments</b>{" "}
                </li>
              </div>
            </ul>
          </div>
        </>
      );
    }
  }
}

1 个答案:

答案 0 :(得分:1)

您应该将待办事项保存在组件状态中,而不是在渲染器中进行计算。

您也不应该有一个名为result的全局变量,也应该将其存储在组件状态中。

这是一个小例子:

fetch(`/admin-completed-workstations`)
      .then(recordset => recordset.json())
      .then(results => {
        this.setState({ questions: results.recordset });
        console.log(this.state.questions);

        // Here, inside getQuestionByUniqueDate you should store result using this.setState instead of having a global variable
        // Then you can simply move the entire renderTodo function outside the render function of this component
        this.state.questions &&
          this.getQuestionByUniqueDate(this.state.questions);
      });

LE:这是一篇有关在React.js应用程序中获取数据的综合文章:

https://www.robinwieruch.de/react-fetching-data(我建议阅读)

LE2:您可以在componentDidMount内部分配结果和待办事项

getQuestionByUniqueDate(questions) {
    const currentResults = this.state.results ? [...this.state.results] : [];
    for (var i = 0; i < questions.length; i++) {
        if (
            !currentResults.find(q => q.Date == questions[i].Date) ||
            !currentResults.find(
                q => q.AssignedWorkStation == questions[i].AssignedWorkStation
            )
        ) {
            currentResults.push(questions[i]);
        }
    }
    return currentResults;
}


fetch(`/admin-completed-workstations`)
    .then(recordset => recordset.json())
    .then(res => {
        const results = res.recordset &&
            this.getQuestionByUniqueDate(res.recordset);
        // Logic for displaying current todos
        const indexOfLastTodo = currentPage * todosPerPage;
        const indexOfFirstTodo = indexOfLastTodo - todosPerPage;
        const currentTodos = results.slice(indexOfFirstTodo, indexOfLastTodo);
        this.setState({
            questions: res.recordset,
            results,
            currentTodos,
            amountOfWorkstations: results.length
        });
    });