Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 使用.map函数将状态传递给子组件_Reactjs - Fatal编程技术网

Reactjs 使用.map函数将状态传递给子组件

Reactjs 使用.map函数将状态传递给子组件,reactjs,Reactjs,我正在制作一个基本页面,显示连接到用户的工作站。 我有一个组件,它调用.map函数中的另一个组件,但是当尝试更新父组件状态时,它似乎没有更新 我能展示这一点的最好方式是通过下面所述的代码演示。(目前它们在同一个文件中,因此当前不需要多个导出语句) 下面是我的父组件,它调用.map函数,然后使用单独的组件将所有工作站映射到下拉按钮中 import React from "react"; import { Link } from "react-router-dom"; import { Modal,

我正在制作一个基本页面,显示连接到用户的工作站。 我有一个组件,它调用.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;
从“React”导入React;
从“react router dom”导入{Link};
从“react bootstrap”导入{Modal,DropdownButton,Dropdown};
类DisplayReact.Component{
构造函数(){
超级();
this.state={questions:[],QuestionsAnswer:[],workstations:[],selectedWorkStation:“};
this.onSubmit=this.handleSubmit.bind(this);
}
//将问题从sql设置为问题的状态
getItems(){
获取(“/用户问题”)
.then(recordset=>recordset.json())
。然后(结果=>{
this.setState({questions:results.recordset});
}); 
}
getWorkStations(){
var user=window.localStorage.getItem(“用户”);
如果(用户){
获取(`/profile工作站详细信息/${user}`)
.then(recordset=>recordset.json())
。然后(结果=>{
this.setState({workstations:results.recordset});
console.log(this.state.workstations)
});
}  
} 
componentDidMount(){
这是我的国家({
问题:this.getItems(),
工作站:this.getWorkStations()
});
}
handleSubmit(e){
e、 预防默认值();
常数数据={
问题ID:这个,问题ID,
提问者回答:这个。州。提问者回答,
问题严重性:this.state.questionsVerity
};
试一试{
获取(“/问题响应”{
方法:“POST”、//或“PUT”
标题:{
接受:“application/json,text/plain,*/*”,
“内容类型”:“应用程序/json”
},
正文:JSON.stringify(数据)
})
.then(response=>response.json())
。然后(数据=>{
console.log(“成功:”,数据);
})
.catch(错误=>{
控制台错误(“错误:”,错误);
});
}捕获(错误){}
}
刷新(){
window.location.reload();
}
render(){
var self=这个;
console.log(this.state.questions);
返回(
案头评估
    案头评估 查看历史 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //在代码的这一部分中,我正在苦苦挣扎 //这将映射显示良好的工作站,但会尝试显示本节最后一行//映射的工作站。这将通过工作站组件进行更新。 {this.state.states&& this.state.workstations.map(函数(工作站,索引){ 返回( ); })}

    所选桌面位置:{this.state.selectedWorkStation} ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// {this.state.problems&& this.state.questions.map(函数(问题,索引){ 返回( ); })}
); } } 导出默认显示问题;
在这个组件中,我试图更新父状态,但是在这个组件中没有任何内容显示在所选的工作站标题中。 在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>

      </>
      );

    }
  }



类WorkStationSelecter扩展React.Component{
建造师(道具){
超级(道具);
控制台日志(道具);
this.state={…props,};
this.selectWorkStation=this.selectWorkStation.bind(this)
}
选择工作站(e)
{
e、 预防默认值()
this.state.selectedWorkStation=this.state.workstations.DeskLocation
警报(此.state.selectedWorkStation)
}
render(){
返回(
{this.state.workstations.DeskLocation}
{this.state.selectedWorkStation}
);
}
}

首先,您正在改变
WorkStationSelecter
组件的状态,这是一种反模式。其次,您正在改变子组件的状态,而不是父组件的状态。如果要更改父级的状态,可以将处理程序传递给子级并在那里调用它。工作站选择器是什么意思?这是我使用道具传递的状态吗?
this.state.selectedWorkStation=this.state.workstations.DeskLocation
这就是我提到的变异。