首页 > 解决方案 > 使用 .map 函数将状态传递给子组件

问题描述

我正在制作一个显示连接到用户的工作站的基本页面。我有一个组件,然后在 .map 函数中调用另一个组件,但是当尝试更新父组件状态时,它似乎没有更新。

我可以展示这一点的最好方法是通过我的代码的演示,如下所述。(这些目前在同一个文件中,因此当前不需要多个导出语句)

下面是我的父组件,它调用一个 .map 函数,然后使用单独的组件将所有工作站映射到下拉按钮。

import React from "react";
import { Link } from "react-router-dom";
import { Modal,DropdownButton,Dropdown } from "react-bootstrap";

class DisplayQuestions extends React.Component {
  constructor() {
    super();

    this.state = { questions: [], QuestionsAnswer: [], workstations: [] , selectedWorkStation: ""};
    this.onSubmit = this.handleSubmit.bind(this);

  }
  // sets the questions form sql into state for questions
  getItems() {
    fetch("/user-questions")
      .then(recordset => recordset.json())
      .then(results => {
        this.setState({ questions: results.recordset });
      }); 

  }


   getWorkStations() {
    var user = window.localStorage.getItem("User");
    if (user) {
      fetch(`/profile-work-station-detailss/${user}`)
        .then(recordset => recordset.json())
        .then(results => {
          this.setState({ workstations: results.recordset });
          console.log(this.state.workstations) 
        });
    }  
  } 

  componentDidMount() {
    this.setState({
      questions: this.getItems(),
       WorkStations :this.getWorkStations()
    });
  }
  handleSubmit(e) {
    e.preventDefault();

    const data = {
      QuestionID: this.QuestionID,
      QuestionsAnswer: this.state.QuestionsAnswer,
      QuestionSeverity: this.state.QuestionsSeverity
    };

    try {
      fetch("/Question-Response", {
        method: "POST", // or 'PUT'
        headers: {
          Accept: "application/json, text/plain, */*",
          "Content-Type": "application/json"
        },
        body: JSON.stringify(data)
      })
        .then(response => response.json())
        .then(data => {
          console.log("Success:", data);
        })
        .catch(error => {
          console.error("Error:", error);
        });
    } catch (error) {}
  }
  refresh() {
    window.location.reload();
  }

  render() {
    var self = this;
    console.log(this.state.questions);
    return (
      <div>
        <h3 style={{ textAlign: "center" }}>
          <u>Desk Assessment</u>
        </h3>

        <ul>
          <button
            disabled
            className="btn btn-secondary"
            style={{ float: "left " }}
          >
            Desk Assessment
          </button>  
          <Link to="./user-history">
            <button className="btn btn-secondary" style={{ float: "left " }}>
              View History
            </button>
          </Link>

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////          

//Within this part of the code is where I am struggling
//This maps the workstations which display fine however last line of this section it tries to display //the workstation mapped. This is updated through the workstation component. 

<DropdownButton style ={{float : "right"}}  id="dropdown-basic-button" title="Select Workstation Location">
{this.state.workstations &&
              this.state.workstations.map(function(workstations, index) { 
                return (
                  <div >
                     <WorkStationSelecter workstations = {workstations}> </WorkStationSelecter>
                  </div>
                );
              })}</DropdownButton> 

<br/>
<br/>          
            <h2 className = "jumbotron">Desk Location Selected : {this.state.selectedWorkStation}</h2>

 /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

            {this.state.questions &&
              this.state.questions.map(function(questions, index) {
                return (
                  <div >


                    <Questions questions={questions}></Questions>

                  </div>
                );
              })}

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

export default DisplayQuestions;

在此组件中,我正在尝试更新父状态,但是其中没有任何内容出现在所选工作站标题中。在 selectWorkStation 中,它会更新此状态并显示在警报中。为什么这没有更新到更高的组件以显示所选择的工作站。


class WorkStationSelecter extends React.Component {
  constructor(props) {
    super(props);
    console.log(props);
    this.state = { ...props,    };
    this.selectWorkStation = this.selectWorkStation.bind(this)
  }

selectWorkStation(e)
{
  e.preventDefault()

 this.state.selectedWorkStation = this.state.workstations.DeskLocation
 alert(this.state.selectedWorkStation)



}
  render() {
      return (
        <>
        <Dropdown.Item onClick={this.selectWorkStation}>{this.state.workstations.DeskLocation} </Dropdown.Item>
        <button>{this.state.selectedWorkStation}</button>

      </>
      );

    }
  }


标签: reactjs

解决方案


推荐阅读