【问题标题】:Collecting all state from mapped components and store state从映射的组件中收集所有状态并存储状态
【发布时间】:2020-02-17 16:25:07
【问题描述】:

我有一个初始组件,它将第二个组件映射到有关问题的信息。我想做的是收集所有这些问题的答案并将它们保存在同一个地方(状态、数组、对象,老实说我不介意如何)。

但是,当我从映射组件更新状态时,它仅在控制台记录这些结果时显示每个单独的更新状态。

我可以如何或在哪里存储此映射组件中的问题答案,以便以后可以使用所有答案存储在其他位置?

这是我提到的映射组件(由于我正在进行的所有条件渲染,这有点令人费解)。


class Questions extends React.Component {
  constructor(props) {
    super(props);
    console.log(props);
    this.state = {
      ...props,
      QuestionAnswer: "",
      QuestionAccepted: false,
      problem: false,

      problemDefinition: "",
      completedQuestions: [],
      soloutionForDeclinedQuestion: ""
    };

    this.QuestionDecline = this.QuestionDecline.bind(this);
    this.QuestionOnChange = this.QuestionOnChange.bind(this);
    this.OnCommit = this.OnCommit.bind(this);
    this.RevertDeclinedAnswer = this.RevertDeclinedAnswer.bind(this);
    this.RevertAcceptedAnswer = this.RevertAcceptedAnswer.bind(this);
    this.AdmitProblem = this.AdmitProblem.bind(this);
    this.AdmitNotProblem = this.AdmitNotProblem.bind(this);
    this.QuestionProblem = this.QuestionProblem.bind(this);
    this.SubmitProblemSoloution = this.SubmitProblemSoloution.bind(this);
    this.submitDeclinedQuestionSoloution = this.submitDeclinedQuestionSoloution.bind(
      this
    );

    this.AcceptAnswer = this.AcceptAnswer.bind(this);
  }
  submitDeclinedQuestionSoloution(e) {
    e.preventDefault();
    let answer = this.state.soloutionForDeclinedQuestion;
    let question = this.state.questions.Question;
    let state = "Declined With solution";

    let newItem = {
      answer: answer,
      question: question,
      state: state
    };
    this.state.completedQuestions.push(newItem);
    console.log(this.state.completedQuestions);


    this.setState({
      QuestionComplete: true,
      QuestionAccepted: false,
      problem: true,
      questionProblem: true,
      problemSubmitted: false,
      declineSubmitted: true
    });
  }

  QuestionDecline(e) {
    e.preventDefault();

    if (this.state.ShowInput) {
      this.setState({ ShowInput: false });
      alert(this.state.ShowInput);
    } else if (!this.state.ShowInput) {
      this.setState({ ShowInput: true });
      alert(this.state.ShowInput);
    }
  }
  AdmitProblem(e) {
    e.preventDefault();
    alert("clicked");

    this.setState({
      QuestionComplete: true,
      QuestionAccepted: true
    });
  }
  AdmitNotProblem(e) {
    e.preventDefault();
    alert("clicked not a problem");

    this.setState({
      QuestionComplete: true,
      QuestionAccepted: false,
      problem: true
    });
  }

  QuestionProblem(e) {
    e.preventDefault();
    alert("problem clicked");

    this.setState({
      QuestionAccepted: false,
      problem: true,
      questionProblem: true,
      QuestionComplete: true
    });
  }

  AcceptAnswer(e) {
    e.preventDefault();
    let answer = "yes";
    let question = this.state.questions.Question;
    let state = "Accepted";

    let newItem = {
      answer: answer,
      question: question,
      state: state
    };
///////////////////////////////////////////////////////////////////////////////////////////////////////////Here I am trying to store to the state.

    this.setState(state => ({
      completedQuestions: state.completedQuestions.concat(newItem)
    }));



    this.setState({
      QuestionAccepted: false,
      problem: false,
      questionProblem: false,
      QuestionComplete: true
    });

    console.log(this.state.QuestionAndAnswer);

  }

  RevertAcceptedAnswer(e) {
    e.preventDefault();
    alert("revert clciked answer declined");
    let Email = window.localStorage.getItem("User");
    let WorkStation = window.localStorage.getItem("Workstation");
    const data = {
      QuestionId: this.state.questions.QuestionId,
      QuestionAnswer: this.state.QuestionAnswer,
      Email,
      WorkStation
    };

    fetch("revert-accepted-question-answer", {
      method: "POST", // or 'PUT'
      headers: {
        Accept: "application/json,",
        "Content-Type": "application/json"
      },
      body: JSON.stringify(data)
    }).then(response => {
      console.log("response before it is broken down " + response);

      // return response.json();
    });
    this.setState({ ShowInput: false, QuestionComplete: false });
    alert("you answer has been deleted from the database");
  }

  RevertDeclinedAnswer(e) {
    e.preventDefault();
    alert("revert clciked answer declined");
    let Email = window.localStorage.getItem("User");
    let WorkStation = window.localStorage.getItem("Workstation");
    const data = {
      QuestionId: this.state.questions.QuestionId,
      QuestionAnswer: this.state.QuestionAnswer,
      Email,
      WorkStation
    };
    fetch("revert-declined-question-answer", {
      method: "POST", // or 'PUT'
      headers: {
        Accept: "application/json,",
        "Content-Type": "application/json"
      },
      body: JSON.stringify(data)
    }).then(response => {
      console.log("response before it is broken down " + response);

      // return response.json();
    });
    this.setState({ ShowInput: false, QuestionComplete: false });
    alert("you answer has been deleted from the database");
  }

  QuestionOnChange(e) {
    this.setState({ QuestionAnswer: e.target.value });
  }

  ///////////////////////////////////////////
  OnCommit(e) {
    alert(this.state.QuestionAnswer);

    var today = new Date(),
      date = `${today.getUTCFullYear()}-${today.getUTCMonth() +
        1}-${today.getUTCDate()} ${today.getHours()}:${today.getMinutes()}:${today.getSeconds()}.${today.getMilliseconds()} `;

    let User = window.localStorage.getItem("User");
    let WorkStation = window.localStorage.getItem("Workstation");

    const data = {
      QuestionId: this.state.questions.QuestionId,
      QuestionAnswer: this.state.QuestionAnswer,
      date: date,
      User,
      WorkStation
    };

    fetch("/declined-question-response", {
      method: "POST", // or 'PUT'
      headers: {
        Accept: "application/json,",
        "Content-Type": "application/json"
      },
      body: JSON.stringify(data)
    }).then(response => {
      console.log("response before it is broken down " + response);

      // return response.json();
    });

    this.setState({ QuestionComplete: true, QuestionAccepted: true });
  }

  SubmitProblemSoloution(e) {
    e.preventDefault();
    let answer = this.state.problemDefinition;
    let question = this.state.questions.Question;
    let state = "problem";

    let newItem = {
      question: question,
      answer: answer,
      state: state
    };
    this.state.completedQuestions.push(newItem);
    console.log(this.state.completedQuestions);

    this.setState({
      QuestionAccepted: false,
      problem: true,
      questionProblem: true,
      problemSubmitted: true
    });
  }

  ////////////////////////////////////////////////
  render() {
    console.log(this.state.completedQuestions);
    ////////////////////////////////////////
    if (!this.state.QuestionComplete) {
      if (!this.state.ShowInput) {
        return (
          <div>
            <div style={{ float: "right" }}>
              <label>{"   "}Problem</label>
              <input
                type="checkbox"
                onClick={this.QuestionProblem}
                className="btn btn-danger"
                style={{ float: "right" }}
              />
            </div>
            <div style={{ float: "right" }}>
              <label>{"   "}No</label>
              <input
                type="checkbox"
                onClick={this.QuestionDecline}
                className="btn btn-danger"
                style={{ float: "right" }}
              />
            </div>

            <div style={{ float: "right" }}>
              <label> {"   "}Yes</label>
              <input
                type="checkbox"
                onClick={this.AcceptAnswer}
                className="btn btn-danger"
                style={{ float: "right" }}
              />
            </div>

            <br />
            <li>{this.state.questions.Question}</li>

            <br />
          </div>
          // </div>
        );
      } else if (
        this.state.ShowInput &&
        !this.state.QuestionComplete &&
        !this.state.problem
      ) {
        return (
          <div>
            <button
              onClick={this.QuestionDecline}
              style={{ float: "right", padding: "2px" }}
              className="btn btn-secondary"
            >
              Revert
            </button>

            <li> Question : {this.state.questions.Question}</li>
            <li>Answer: No</li>
            <li>
              Is this causing you a Problem?{" "}
              <div style={{ float: "right" }}>
                <label>{"   "}No</label>
                <input
                  type="checkbox"
                  onClick={this.AdmitNotProblem}
                  className="btn btn-danger"
                  style={{ float: "right" }}
                />
              </div>
              <div style={{ float: "right" }}>
                <label> {"   "}Yes</label>
                <input
                  type="checkbox"
                  onClick={this.AdmitProblem}
                  className="btn btn-danger"
                  style={{ float: "right" }}
                />
                <br />
                <br />
                <br />
              </div>
            </li>

            <br />
          </div>
        );
      }
    } else if (this.state.QuestionComplete) {
      if (
        this.state.QuestionAccepted &&
        !this.state.problem &&
        !this.state.questionProblem &&
        !this.state.problemSubmitted &&
        !this.state.declineSubmitted
      ) {
        return (
          <h3>
            <button
              onClick={this.RevertDeclinedAnswer}
              style={{ float: "right" }}
              className="btn btn-danger"
            >
              {" "}
              Revert Answer
            </button>
            <br />

            <li style={{ textAlign: "center", color: "grey" }}>
              <b>{this.state.questions.Question}</b>
            </li>

            <textarea
              placeholder="What would you suggest we do to solve this? "
              style={{ width: "100%" }}
              onChange={e =>
                this.setState({ soloutionForDeclinedQuestion: e.target.value })
              }
            />
            <button
              onClick={this.submitDeclinedQuestionSoloution}
              className="btn btn-primary"
              style={{ width: "100%" }}
            >
              Submit suggestion
            </button>
          </h3>
        );
      } else if (
        !this.state.QuestionAccepted &&
        !this.state.problem &&
        !this.state.questionProblem &&
        !this.state.problemSubmitted &&
        !this.state.declineSubmitted
      ) {
        return (
          <h3>
            <button
              onClick={this.RevertAcceptedAnswer}
              style={{ float: "right" }}
              className="btn btn-danger"
            >
              {" "}
              Revert Answer
            </button>
            <br />

            <li style={{ textAlign: "center", color: "grey" }}>
              <b>{this.state.questions.Question}</b>
            </li>
            <li>
              <b>Status</b>: Yes
            </li>
            <li>Complete : ✔️ </li>
          </h3>
        );
      } else if (
        !this.state.QuestionAccepted &&
        this.state.problem &&
        !this.state.questionProblem &&
        !this.state.problemSubmitted &&
        !this.state.declineSubmitted
      ) {
        return (
          <h3>
            <button
              onClick={this.RevertAcceptedAnswer}
              style={{ float: "right" }}
              className="btn btn-danger"
            >
              {" "}
              Revert Answer
            </button>
            <br />
            <li style={{ textAlign: "center", color: "grey" }}>
              <b>{this.state.questions.Question}</b>
            </li>
            <li>
              <b>Status</b>: No but not a problem
            </li>
            <li>Complete : ✔️ </li>
          </h3>
        );
      } else if (
        !this.state.QuestionAccepted &&
        this.state.problem &&
        this.state.questionProblem &&
        !this.state.problemSubmitted &&
        !this.state.declineSubmitted
      ) {
        return (
          <>
            <h3>
              <button
                onClick={this.RevertAcceptedAnswer}
                style={{ float: "right" }}
                className="btn btn-danger"
              >
                {" "}
                Revert Answer
              </button>
              <br />
              <li> {this.state.questions.Question} </li>

              <textarea
                style={{ width: "100%" }}
                onChange={e =>
                  this.setState({ problemDefinition: e.target.value })
                }
                placeholder={`Please specify the problem`}
              />
            </h3>
            <button
              style={{ width: "100%" }}
              className="btn btn-primary"
              onClick={this.SubmitProblemSoloution}
            >
              Submit Solution{" "}
            </button>
          </>
        );
      } else if (
        !this.state.QuestionAccepted &&
        this.state.problem &&
        this.state.questionProblem &&
        this.state.problemSubmitted &&
        !this.state.declineSubmitted
      ) {
        return (
          <>
            <h3>
              <button
                onClick={this.RevertAcceptedAnswer}
                style={{ float: "right" }}
                className="btn btn-danger"
              >
                {" "}
                Revert Answer
              </button>
              <br />
              <li style={{ textAlign: "center", color: "grey" }}>
                {" "}
                <b>{this.state.questions.Question}</b>{" "}
              </li>{" "}
              <li>
                <b>Status</b>: Problem with soloution submitted
              </li>
              <li>
                <b>Soloution: </b>
                {this.state.problemDefinition}
              </li>
              <li>Complete : ✔️ </li>
            </h3>
          </>
        );
      } else if (
        !this.state.QuestionAccepted &&
        this.state.problem &&
        this.state.questionProblem &&
        !this.state.problemSubmitted &&
        this.state.declineSubmitted
      ) {
        return (
          <>
            <h3>
              <button
                onClick={this.RevertAcceptedAnswer}
                style={{ float: "right" }}
                className="btn btn-danger"
              >
                {" "}
                Revert Answer
              </button>
              <br />
              <li style={{ textAlign: "center", color: "grey" }}>
                {" "}
                <b>{this.state.questions.Question}</b>{" "}
              </li>{" "}
              <li>
                <b>Status</b>: Declined with soloution defined
              </li>
              <li>
                <b>Soloution: </b>
                {this.state.soloutionForDeclinedQuestion}
              </li>
              <li>Complete : ✔️ </li>
            </h3>
          </>
        );
      }
    }
  }
}

由于这个组件太大了,我想把它分解成更简单的块以获得最佳建议。

下面只是一个accept answer onclick方法


  AcceptAnswer(e) {
    e.preventDefault();
    let answer = "yes";
    let question = this.state.questions.Question;
    let state = "Accepted";

    let newItem = {
      answer: answer,
      question: question,
      state: state
    };

    this.setState(state => ({
      completedQuestions: state.completedQuestions.concat(newItem)
    }));


但是,当控制台在此组件的任何位置登录时,它只会显示最近回答的问题。

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    我用我认为可能的最简单方法解决了这个问题。 我希望有一种更鼓舞人心的方式来做到这一点,但这就是我最终的结果。

    我所做的只是在我的第一堂课的顶部定义一个数组,然后将所有这些结果推送到那里。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-18
      • 2015-07-31
      • 2018-09-13
      • 1970-01-01
      • 2020-04-22
      • 1970-01-01
      • 2018-08-09
      • 2020-02-22
      相关资源
      最近更新 更多