根据不同的按钮单击来更新状态

时间:2020-06-05 10:41:40

标签: javascript reactjs firebase axios state

我正在尝试使用Firebase制作调查工具并做出反应,并且正在实现模板功能,所以现在其中一个模板正在运行,当用户单击创建新调查时,向他们显示了各种按钮,例如:空白,temp1,temp2,temp3,temp4基于触发单击处理程序的任何单击,现在如何根据我要获取的模板来更新状态的内容?下面是我的代码:

<button onClick={props.clicked} className={classes.Board}>
        Board Survey
      </button>
      <button onClick={props.chair} className={classes.Chair}>
        Chairperson Survey
      </button>
      <button onClick={props.member} className={classes.Member}>
        Board Member Survey
      </button>

现在我用

clicked={this.clickHandler}

要获取调查模板的代码:

const fetchSurvey = async () => {
  const res = await axios.get(
    "/surveys/ckb0kmt3n000e3g5rmjnfw4go/content/questions.json"
  );
  return res.data;
};

其中“ ckb0kmt3n000e3g5rmjnfw4go”是调查ID

 const content = {
  title: "Your Survey Tite",
  subTitle: "Your Survey Description",
  creatorDate: new Date(),
  lastModified: new Date(),
  questions: fetchSurvey().then(questions => {
    this.setState(state => ({
      ...state,
      content: {
        ...state.content,
        questions
      }
    }));
  }),
  submitting: true
};

this.setState({
  _id: newId(),
  content: content,
  userId: this.props.user_Id
});
}

现在我该如何根据上一页选择的模板来更新问题键以运行不同的功能?

ClickHandler代码:

clickHandler = () => {
const newSurvey = { ...this.state };
axios
  .put(
    "/surveys/" + this.state._id + ".json?auth=" + this.props.token,
    newSurvey
  )
  .then(res => {
    this.props.onGetSurveyId(res.data._id);
  })
  .catch(error => {
    console.log(error);
  });

};

文件1:

    import React from "react";
import Button from "@material-ui/core/Button";
import Icon from "@material-ui/core/Icon";
import { makeStyles } from "@material-ui/core/styles";
import classes from "./NewSurvey.module.css";
import { Link } from "react-router-dom";
import Dialog from "@material-ui/core/Dialog";
import DialogActions from "@material-ui/core/DialogActions";
import DialogContent from "@material-ui/core/DialogContent";
import DialogTitle from "@material-ui/core/DialogTitle";
import InputLabel from "@material-ui/core/InputLabel";
import Input from "@material-ui/core/Input";
import MenuItem from "@material-ui/core/MenuItem";
import FormControl from "@material-ui/core/FormControl";
import Select from "@material-ui/core/Select";
import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";

const NewSurvey = props => {
  const [open, setOpen] = React.useState(false);
  const [template, setTemplate] = React.useState("");

  const handleChange = event => {
    setTemplate(Number(event.target.value) || "");
  };

  const handleClickOpen = () => {
    setOpen(true);
  };

  const handleClose = () => {
    setOpen(false);
  };

  const notify = () =>
    toast.info("Creating Survey....Please Wait", {
      position: "top-right",
      autoClose: 5000,
      hideProgressBar: true,
      closeOnClick: true,
      pauseOnHover: true,
      draggable: true,
      progress: undefined
    });

  return (
    <div className={classes.CreateSurvey}>
      <ToastContainer
        position="top-right"
        autoClose={5000}
        hideProgressBar
        newestOnTop
        closeOnClick
        rtl={false}
        pauseOnFocusLoss
        draggable
        pauseOnHover
      />
      <Dialog
        disableBackdropClick
        disableEscapeKeyDown
        open={open}
        onClose={handleClose}
        className={classes.Dialog}
      >
        <DialogTitle className={classes.DialogTitle}>
          Create New Survey
        </DialogTitle>
        <h5 className={classes.Info}>
          Choose a template or start with a blank survey
        </h5>
        <DialogContent>
          <button
            onClick={function(event) {
              props.clicked();
              notify();
            }}
            className={classes.Blank}
          >
            Blank Survey
          </button>
          <button onClick={props.board} className={classes.Board}>
            Board Survey
          </button>
          <button onClick={props.chair} className={classes.Chair}>
            Chairperson Survey
          </button>
          <button onClick={props.member} className={classes.Member}>
            Board Member Survey
          </button>
        </DialogContent>
        <DialogActions>
          <button onClick={handleClose} className={classes.CancelButton}>
            Cancel
          </button>
        </DialogActions>
      </Dialog>
      <button
        className={classes.NewSurvey}
        onClick={handleClickOpen}
        disabled={props.isLoading || props.error}
      >
        <Icon className={classes.Icon}>add_circle_outline</Icon> Create New
        Survey
      </button>
    </div>
  );
};

export default NewSurvey;

文件2:

import React, { Component } from "react";
import { withRouter } from "react-router-dom";
import { connect } from "react-redux";
import newId from "../../../ulitity/idGenerator";
import axios from "../../../axios-order";

import * as actionTypes from "../../../Store/actions/actionsTypes";
import NewSurveyView from "../../../Components/NewSurvey/NewSurvey";
import { InitQuestions } from "../../../ulitity/constants/Questions";

class NewSurvey extends Component {
  state = {
    _id: "",
    userId: "",
    content: {
      title: "Your Survey Title",
      subTitle: "",
      creatorDate: "",
      lastModified: ""
    }
  };
  componentDidMount() {
    var sampleQuestion;
    var questionObj;
    sampleQuestion = InitQuestions["SINGLE_LINE_TEXT"]();
    questionObj = {
      [sampleQuestion._id]: sampleQuestion
    };
    var orderQuestions;
    let questions = [sampleQuestion._id];
    orderQuestions = questions.map(questionId => questionObj[questionId]);
    const fetchBoardMember = async () => {
      const res = await axios.get(
        "/surveys/ckb0kmt3n000e3g5rmjnfw4go/content/questions.json"
      );
      return res.data;
    };

    const fetchBoard = async () => {
      const res = await axios.get(
        "/surveys/ckb24goc800013g5r7j8igrk3/content/questions.json"
      );
      return res.data;
    };

    const fetchChair = async () => {
      const res = await axios.get(
        "/surveys/ckb24gt3s00053g5rrf60353r/content/questions.json"
      );
      return res.data;
    };

    const content = {
      title: "Your Survey Title",
      subTitle: "Your Survey Description",
      creatorDate: new Date(),
      lastModified: new Date(),
      questions: fetchBoard().then(questions => {
        this.setState(state => ({
          ...state,
          content: {
            ...state.content,
            questions
          }
        }));
      }),
      submitting: true
    };

    this.setState({
      _id: newId(),
      content: content,
      userId: this.props.user_Id
    });
  }

  clickHandler = () => {
    const newSurvey = { ...this.state };
    axios
      .put(
        "/surveys/" + this.state._id + ".json?auth=" + this.props.token,
        newSurvey
      )
      .then(res => {
        this.props.onGetSurveyId(res.data._id);
      })
      .catch(error => {
        console.log(error);
      });
  };

  render() {
    return (
      <div>
        <NewSurveyView
          clicked={this.clickHandler}
          board={this.boardHandler}
          chair={this.chairHandler}
          member={this.memberHandler}
          isLoading={this.props.loading}
          error={this.props.isError}
        />
      </div>
    );
  }
}

const mapStateToProps = state => {
  return {
    user_Id: state.auth.userId,
    token: state.auth.token,
    surveyId: state.surveyEditer.survey.id
  };
};

const mapDispatchToProps = dispatch => {
  return {
    onGetSurveyId: surveyId =>
      dispatch({ type: actionTypes.GET_SURVEY_ID, surveyId: surveyId })
  };
};

export default withRouter(
  connect(mapStateToProps, mapDispatchToProps)(NewSurvey)
);

0 个答案:

没有答案