【问题标题】:how can I store input data to an options of array?如何将输入数据存储到数组选项中?
【发布时间】:2021-01-24 10:03:09
【问题描述】:

这是我的 react 和 nodejs 代码,我想在其中使用 react 表单创建民意调查,但我不明白我的代码出了什么问题...!`这里我有 4 个输入字段,带有 { option1: "", option2 : "", option3: "", option4: "" },但我不知道如何存储数据,就像我使用 POSTMAN 存储数据一样......!任何人都可以帮助请帮助....! 反应 JS 代码--->

import React, { useState, useEffect } from "react";
import "../styles.css";
import { isAutheticated } from "../auth/helper/index";
import { createaPoll } from "./helper/adminapicall";

const AddPoll = () => {
  const { user, token } = isAutheticated();
  const [value, setValue] = useState({
    question: "",
    options: { option1: "", option2: "", option3: "", option4: "" },
    error: "",
    loading: "false",
    getRedirect: false,
    formData: "",
  });

  const { question, options, error, loading, getRedirect, formData } = value;

  const handleChange = (event) => {
    // setError("");
    setValue({ ...value, [event.target.name]: event.target.value });
    // console.log(event.target.value);
    const newOption = {
      ...value.options,
      [event.target.name]: event.target.value,
    };
    setValue((prev) => ({ ...prev, options: newOption }));
  };

  const onSubmit = (event) => {
    event.preventDefault();
    setValue({ ...value, error: "", loading: true });
    // console.log(handel);
    const { option1, option2, option3, option4 } = options;
    const newOptions = [option1, option2, option3, option4];
    createaPoll(user._id, token, { question, options: newOptions }).then(
      (data) => {
        console.log(data);
        if (data.error) {
          setValue({ ...value, error: data.error });
        } else {
          setValue({
            ...value,
            question: "",
            options: { option1: "", option2: "", option3: "", option4: "" },
            error: "",
            loading: "false",
            getRedirect: false,
            formData: "",
          });
        }
      }
    );
  };

  return (
    <div className="AddPoll">
      <div className="container">
        <h1>Add New Poll</h1>
        <form>
          <textarea
            rows="4"
            cols="50"
            className="form-control mb-2"
            placeholder="Question"
            name="question"
            value={question}
            onChange={(event) => handleChange(event)}
            autoFocus
          ></textarea>
          <input
            type="text"
            className="form-control mb-2"
            placeholder="Option1"
            onChange={(event) => handleChange(event)}
            name="option1"
            value={options.option1}
          />
          <input
            type="text"
            className="form-control mb-2"
            placeholder="Option2"
            onChange={(event) => handleChange(event)}
            name="option2"
            value={options.option2}
          />
          <input
            type="text"
            className="form-control mb-2"
            placeholder="Option3"
            onChange={(event) => handleChange(event)}
            name="option3"
            value={options.option3}
          />
          <input
            type="text"
            className="form-control mb-2"
            placeholder="Option4"
            onChange={(event) => handleChange(event)}
            name="option4"
            value={options.option4}
          />
          <button type="submit" onClick={onSubmit} className="btn Submitbtn">
            Submit
          </button>
        </form>
      </div>
    </div>
  );
};

export default AddPoll;

节点代码--->

exports.createPolls = async (req, res, next) => {
  try {
    const { question, options } = req.body;
    const dynamic = {};
    options.forEach((opt) => {
      dynamic[opt.toLowerCase()] = [];
    });
    const polls = await Poll.create({
      question,
      options: dynamic,
    });
    polls.save((err, polls) => {
      if (err) {
        res.status(400).json({
          error: "Saving Poll in DB failed",
        });
      }
      res.json(polls);
    });
  } catch (error) {
    error.status = 400;
    next(error);
  }
};

当我使用 POSTMAN 时,它工作正常!这是我的邮递员图片

每当我使用反应表单单击提交按钮时,反应表单上都会出现错误(未处理的拒绝(TypeError):无法读取未定义的属性'错误')在行号 - 39

当我检查我的节点服务器时,它也会显示一个错误(无法读取未定义的属性 'forEach') 我不明白为什么会这样......!因为 POSTMAN 可以正常使用此代码,但不能对表单做出反应,,,!请帮忙...!

【问题讨论】:

  • data.error console.log() 是什么?
  • data.error console.log() 是什么? --- 未定义

标签: node.js reactjs mongodb express mern


【解决方案1】:

options 必须是一个数组才能使用 forEach 方法对其进行迭代

【讨论】:

    【解决方案2】:

    错误响应需要放在 catch() 块中的 then() 块之后。您可以使用 err.response.data.error 定位 err 响应数据以获取您的消息。这样任何 response.status !== 200 都可以有自己的语句。

     const onSubmit = (event) => {
        event.preventDefault();
        setValue({ ...value, error: "", loading: true });
        // console.log(handel);
        const { option1, option2, option3, option4 } = options;
        const newOptions = [option1, option2, option3, option4];
        createaPoll(user._id, token, { question, options: newOptions }).then(
          (data) => {
              setValue({
                ...value,
                question: "",
                options: { option1: "", option2: "", option3: "", option4: "" },
                error: "",
                loading: "false",
                getRedirect: false,
                formData: "",
              }).catch((err) => {
              console.log(err.response.data.error)
              setValue({ ...value, error: err.response.data.error });
              });
            }
          }
        );
      };

    【讨论】:

    • nodejs 服务器错误 - (无法读取未定义的属性“forEach”)
    • 和 reactjs 错误 - 未处理的拒绝(TypeError):无法读取未定义的属性 'catch'
    【解决方案3】:

    如果选项只是字符串,只需将它们放在一个数组中并将它们传递给您的 req 对象,如下所示:

    const onSubmit = (event) => {
        event.preventDefault();
        setValue({ ...value, error: "", loading: true });
        // console.log(handel);
        const { option1, option2, option3, option4 } = options;
        const newOptions = [option1, option2, option3, option4];
        createaPoll(user._id, token, { question, newOptions }).then( //like this
          (data) => {
              setValue({
                ...value,
                question: "",
                options: { option1: "", option2: "", option3: "", option4: "" },
                error: "",
                loading: "false",
                getRedirect: false,
                formData: "",
              }).catch((err) => {
              console.log(err.response.data.error)
              setValue({ ...value, error: err.response.data.error });
              });
            }
          }
        );
      };

    然后 console.log 你的 newOptions 数组和 req.body 在你的路由中,看看你的数据是否被正确引导,

    exports.createPolls = async (req, res, next) => {
      try {
        const { question, options } = req.body;
        console.log(question, options, req.body) // what does this look like?
        const dynamic = {};
        options.forEach((opt) => {
          dynamic[opt.toLowerCase()] = [];
        });
        const polls = await Poll.create({
          question,
          options: dynamic,
        });
        polls.save((err, polls) => {
          if (err) {
            res.status(400).json({
              error: "Saving Poll in DB failed",
            });
          }
          res.json(polls);
        });
      } catch (error) {
        error.status = 400;
        next(error);
      }
    };

    也许数据没有被传递到路由属性?

    【讨论】:

    • console.log(question, options, req.body) ---> undefined undefined {} TypeError: Cannot read property 'forEach' of undefined
    • 当路由甚至没有数据时,如何将数据保存到您的数据库中?检查 react chrome 开发工具扩展以确保您的前端选择正在设置。
    猜你喜欢
    • 1970-01-01
    • 2021-04-27
    • 2017-11-18
    • 2011-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-27
    • 2023-03-25
    相关资源
    最近更新 更多