首页 > 解决方案 > .map 中的嵌入函数以访问映射信息

问题描述

我正在使用 .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>
        </>
      );
    }
  }
}

标签: javascriptreactjs

解决方案


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

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

这是一个小例子:

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
        });
    });

推荐阅读